在函数中重新分配后出现分段错误

Segmentation fault after realloc in function

我创建了这段代码来测试一个错误,我在主代码中遇到了这个错误,它也有同样的问题。我总是收到分段错误或损坏的数据(零或奇怪的数字)。

代码如下:

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;
}  

我在 *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;