【问题标题】:Why does my void pointer change values in my program?为什么我的 void 指针在我的程序中改变值?
【发布时间】: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)

标签: c pointers malloc void


【解决方案1】:

您正在返回一个局部变量的地址,这是 C 中未定义的行为。

如果你想返回一个指针,它指向的内存必须在返回它的函数的作用域之外。因为您正在返回一个指向局部变量 item 的指针,所以当函数返回时,该内存位置不再可用。

我想你搞错了。您确实分配了内存,但复制不正确。

SortedListPtr ptr = (struct SortedList *) malloc(sizeof(struct SortedList));    
ptr = &item;

这里用本地item的地址替换指针。相反,最后一行应该是:

*ptr = item;

上面会将item中存储的所有数据复制到ptr引用的内存位置。

还有一件事...我很确定您不应该为previous 和next 分配东西。只需将它们设置为NULL。如果没有看到您打算如何使用它,我无法确定,但我可以看到您对指针感到困惑。这会更“正常”:

item.next = NULL;
item.previous = NULL;

【讨论】:

  • malloc() 在函数开始时构造结构并直接设置其成员会更好。
  • 是的,当然。我想我也不想把这些都写出来。
  • 由于struct中没有拷贝构造函数,并且使用指针作为成员变量,所以当item被析构时(如果有的话),*ptr = item可能会引入其他问题?
  • @michaeltang 这是 C,不是 C++。
  • 谢谢。那么如何 malloc 分配的内存并将其保持为空。我有一个场景,我不能说 *(pointer) = NULL,因为指针指向一个结构。但是,稍后在程序中,指针被分配了一个我不想要的随机内存。我想保持它为空。我该怎么做?
【解决方案2】:

可能这种方式可以减少副本。因为我不确定你是否有复制结构

SortedListPtr SLCreate(CompareFuncT cf, DestructFuncT df)
{
    SortedListPtr ptr = (struct SortedList *) malloc(sizeof(struct SortedList));    

    ptr->data = malloc(100);
    ptr->data = NULL;           
    ptr->next = (struct SortedList *) malloc(sizeof(struct SortedList));
    ptr->previous = (struct SortedList *) malloc(sizeof(struct SortedList));
    ptr->compareFunc = cf;
    ptr->destructor = df;
    return ptr;
};

【讨论】:

    猜你喜欢
    • 2011-11-12
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多