C++中函数调用使用指针出现0xC0000005错误无法输出预期数值
错误原因分析
你遇到的报错码0xC0000005是Windows平台下的访问违例错误(也常称段错误),本质是程序访问了无权限操作的内存地址,你的代码存在3个核心问题:
- 指针参数值传递导致修改不生效:Test函数的
int* Ptr是形参,属于函数内的局部变量,给Ptr赋值malloc返回的地址,只会修改当前函数内的局部副本,main函数里的m_Ptr仍然是空指针(值为0),后续执行m_Ptr[0]属于访问空指针地址,直接触发访问违例。 - 语法错误:
printf代码行末尾缺少闭合的右括号,编译阶段就会抛出语法错误。 - 不规范问题:Test函数未声明返回值、malloc参数写固定值兼容性差;旧C标准默认函数返回值为int,你的Test函数无return语句属于不规范写法;
malloc(8)默认假设int占4字节,在int长度不为4的平台上会出现越界访问,兼容性差。
修复方案
方案1:传递二级指针,让函数可以修改外部指针的指向
#include <stdio.h> #include <stdlib.h> // 传入二级指针,直接修改外部指针的地址 void Test(int** Ptr) { *Ptr = (int*)malloc(2 * sizeof(int)); if(*Ptr == NULL) { printf("malloc error\n"); return; } (*Ptr)[0] = 155; (*Ptr)[1] = 800; } int main() { int* m_Ptr = NULL; // 传入指针的地址 Test(&m_Ptr); if(m_Ptr != NULL) { printf("%d %d", m_Ptr[0], m_Ptr[1]); // 释放堆内存避免泄漏 free(m_Ptr); m_Ptr = NULL; } return 0; }
方案2:让Test函数返回malloc后的指针地址
#include <stdio.h> #include <stdlib.h> int* Test() { int* Ptr = (int*)malloc(2 * sizeof(int)); if(Ptr == NULL) { printf("malloc error\n"); return NULL; } Ptr[0] = 155; Ptr[1] = 800; return Ptr; } int main() { int* m_Ptr = Test(); if(m_Ptr != NULL) { printf("%d %d", m_Ptr[0], m_Ptr[1]); free(m_Ptr); m_Ptr = NULL; } return 0; }
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

