Mat*_*ens 2 c pointers realloc double-pointer
我已经创建了这个代码来测试一个错误,我在主代码中得到了它,并且它共享同样的问题.我总是得到分段错误或损坏的数据(零或奇数).
这是代码:
int *p=NULL;
int func (int **point);
int main() {
int num = 5647;
p = malloc(sizeof(int)*2);
p[0] = num;
p[1]= 657;
printf("%d\n", p[0]);
printf("%d\n", p[1]);
func(&p);
printf("%d\n", p[0]);
printf("%d\n", p[1]);
printf("%d\n", p[2]);
printf("%d\n", p[3]);
return 0;
}
int func (int **point){
*point = realloc(*point,sizeof(int)*4);
if (*point==NULL){
printf("\n abort \n");
exit(0);
}
*point[0] = 867;
*point[1]= 777;
*point[2] = 67;
*point[3]= 77;
}
Run Code Online (Sandbox Code Playgroud)
我正在获得分段错误*point[1]=777;.如果我试图这样做,point[1]=777;我会得到错误的数据.随着任何变化int func (int **point);或func(&p);我正在进行分段故障realloc.
请指教,我已阅读有关双指针的信息,并试图按照我找到的所有解决方案,但每次我收到此错误.
您的问题是运营商优先级,更改*point[0]为(*point)[0]等等.
你现在拥有的是什么*(point[0]).您将指向单个元素的指针视为指向多个连续元素的指针,然后将某些不确定值取消引用作为地址.这导致了未定义的行为,幸运的是,您表现为崩溃.
更改后,首先取消引用 point,然后使用该地址索引到您分配的连续元素.
两项改进建议:
不要realloc直接分配结果*point.如果调用失败,则泄漏原始内存.首先将其分配给临时用于验证.
另外,尽量不要重复类型.而不是sizeof(int)尝试sizeof(**point),即输出缓冲区应指向的任何内容.这样,如果将类型更改为其他类型,则代码中不会出现静默错误int.
void *point_check = realloc(*point,sizeof(**point)*4);
if (point_check == NULL){
printf("\n abort \n");
exit(0); // If this ever returns instead of exit, `*point` will not leak
}
*point = point_check;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
381 次 |
| 最近记录: |