【发布时间】:2014-02-17 01:07:03
【问题描述】:
我在头文件中有以下内容。
struct SortedList
{
void * data;
struct SortedList * next;
struct SortedList * previous;
int (*compareFunc)(void *, void *);
void (*destructor)(void *);
};
typedef struct SortedList* SortedListPtr;
SortedListPtr SLCreate(CompareFuncT cf, DestructFuncT df);
在一个 .c 文件中,我实现了 SLCreate 函数。
SortedListPtr SLCreate(CompareFuncT cf, DestructFuncT df)
{
struct SortedList item;
item.data = malloc(100);
item.data = NULL;
item.next = (struct SortedList *) malloc(sizeof(struct SortedList));
item.previous = (struct SortedList *) malloc(sizeof(struct SortedList));
item.compareFunc = cf;
item.destructor = df;
SortedListPtr ptr = (struct SortedList *) malloc(sizeof(struct SortedList));
ptr = &item;
return ptr;
};
在 main.c 中,我尝试执行以下操作: SortedListPtr list = SLCreate(&compareInts, &destroy);
//...... A bunch other code that does not alter list or it's contents at all.
struct SortedList item = (*list);
void * data = item.data;
if (data != NULL)
{
printf("Why did data become not null???\n");
}
那么,为什么我在 SLCreate 函数中指定的数据不为空?我以为我使用了 malloc,我该怎么做才能解决这个问题?
【问题讨论】:
-
将 item.data 设置为 malloc() 的返回值,然后将其设置为 NULL 会丢弃分配的内存。如果要将分配的内存归零,则需要这样做。 (查找 memset)