【发布时间】:2011-07-18 02:40:25
【问题描述】:
为什么会导致段错误??
#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() 分配的内存也映射到 main 中的 malloc() 分配的内存..
但这怎么会发生呢?内存管理器(我猜这里的 lib(stdlib))不跟踪进程中的空闲和分配空间吗?
【问题讨论】:
-
如果 realloc 移动指针,即分配器中的“tmp”与“ptr”不同,那么在调用函数(main)中,ptr 不再是有效指针。您需要将更改后的指针返回到 main。
-
是的,是的......但我试图重新分配 int 指针数组而不是结构节点本身......即 realloc(ptr->darray, 10) 挣扎了一个小时左右它....只能在收到 cmets 后才发现这个愚蠢的错误解决了无论如何谢谢
标签: c memory memory-management