需要一些帮助来理解C中的指针和内存

时间:2010-01-29 02:24:50

标签: c memory pointers memory-management

我正在为一个类编写一些代码,但由于我没有C语言的经验,我有点不确定我编写的代码实际上是做什么的。特别是内存的样子。这是相关的部分:

typedef struct listnode *Node;
typedef struct listnode {
    void *data;
    Node next;
    Node previous;
} Listnode;

typedef struct listhead *LIST;
typedef struct listhead {
    int size;
    Node first;
    Node last;
    Node current;
} Listhead;

#define HALLOCSIZE 50

static LIST hallocbuf[HALLOCSIZE];
static LIST *hallocp = hallocbuf;

LIST *CreateList()
{
    if(hallocbuf + HALLOCSIZE - hallocp >= 1)
    {
        LIST temp;
        temp->size = 0;
        temp->first = NULL;
        temp->last = NULL;
        temp->current = NULL;

        *hallocp = temp;
        return hallocp;

    }else
        return NULL;
}

所以我的问题是,在CreateList函数中,程序如何为temp分配内存?代码*hallocp = temp是否将临时LIST复制到hallocbuf数组中?我试图让所有的LIST结构都位于为hallocbuf分配的内存中。这是我在做什么的?我有点不确定typedef,structs和指针如何一起发挥。

谢谢!

3 个答案:

答案 0 :(得分:4)

  

所以我的问题是,在CreateList函数中,程序如何为temp分配内存?

不是,这是一个问题。它应该这样的事情:

temp = malloc(sizeof(Listhead));
  

代码* hallocp = temp是否将临时LIST复制到hallocbuf数组中?

它将temp中保存的指针复制到hallocbuf的第一个元素中(假设hallocp未在任何地方更改,并且仍具有已初始化的值指向hallocbuf[0])。

通常,隐藏LISTNode是typedef背后的指针的事实通常不是一个好主意。如果明显哪些变量是指针,并且在变量声明中有明确的*就可以清楚地表明内存需要分配释放的内容更清楚了。

答案 1 :(得分:3)

temp分配在用于具有“自动存储持续时间”的对象的空间中 - 这通常在运行时堆栈上,但您实际上并不需要知道详细信息。当退出分配的块时(在您的情况下,当您点击return时),该空间将被释放。

*hallocp = temp;确实将temp的值复制到hallocp指向的内存中,即hallocbuf[0]

问题是temp只是一个指针本身 - 而且它并没有将指向任何东西。这被称为“悬空指针”。这意味着当您尝试访问它所指向的内容时,您会出错。这种情况发生在以下几行:

temp->size = 0;
temp->first = NULL;
temp->last = NULL;
temp->current = NULL;

你不能让你的结构分配给hallocbuf的内存中,因为它没有结构空间 - 它只是一个指针数组,而不是一个数组结构

答案 2 :(得分:0)

如果LIST是

typedef struct listhead LIST;

你访问了临时

temp.size = 0;
...

然后

*hallocp++ = temp;

将使用hallocp作为指向hallocbuf缓冲区的指针,并将新初始化的元素放在那里。不过,这不是最好的方法。您可以用

替换temp
hallocp->size = 0;
...
++hallocp;