Basic Malloc/Free

前端 未结 5 500
谎友^
谎友^ 2021-01-20 18:50

If I have a snippit of my program like this:

struct Node *node;
while(...){
    node = malloc(100);
    //do stuff with node
}

This means t

5条回答
  •  北海茫月
    2021-01-20 19:31

    If you set node = NULL before the loop and then use free(node) before node = malloc(100) you should be OK. You will also need to do a free(node) after the loop exits. But then again, it all depends on what "//do stuff with node" actually does. As others have pointed out, malloc(100) is not a good idea. What I would use is malloc(sizeof(*node)). That way, if the type of node changes, you don't have to change the malloc line.

提交回复
热议问题