爲什麼這樣會導致段錯誤?我的最愛Segfault !!爲什麼?
#include<stdio.h>
#include<stdlib.h>
struct node
{
double d;
int *array;
char c;
};
void allocator(struct node *ptr)
{
int *tmp;
tmp = (int*)realloc(ptr, 10);
if(!tmp)
{
ptr->array=tmp;
ptr->array[0] = 23;
}
}
int
main()
{
struct node *ptr = (struct node*)malloc(sizeof(struct node));
ptr->c = 'y';
allocator(ptr);
printf(" %c\n", ptr->c);
printf(" %d\n", ptr->array[0]);
return 0;
}
我得到的印象好像realloc的()中的分配部的功能分配內存,這也映射到在主的malloc()分配的內存..
但這是如何發生的? ?不是內存管理器(我猜這裏是lib(stdlib))跟蹤進程中的空閒空間和分配空間嗎?
如果realloc移動指針,即分配器中的「tmp」與「ptr」不同,那麼在調用函數(main)中,ptr不再是有效的指針。您需要將更改後的指針返回到main。 –
是啊真正的......但我試圖重新分配int指針數組而不是結構節點本身....即realloc(ptr-> darray,10)在一小時左右努力掙扎......只能發現這個愚蠢的錯誤解決它後收到評論在這裏感謝反正 – raja