简体   繁体   中英

Returning a pointer or a reference in C

Having the following,

struct node{
    int value;
    struct node *next;
};

typedef struct node Node;
typedef struct node *pNode;

Node newNode(){
    Node n;
    n.value = 5;
    return n;
}

pNode newpNode(){
    pNode pn = (pNode) malloc(sizeof(Node));
    pn->value = 6;
    return pn;
}

I read somewhere that if memory deallocation is to be done by the caller function, I should use newpNode(), and otherwise use newNode(), but that does not help me understand quite enough.

Can you give me some concrete examples of when should I use newNode() and when newpNode()?

Edit: forgot pn inside newpNode()

In this simple example, there is no strong need to use one over the other.

When you call newNode(), memory is allocated when the function is called to store the size of a Node to be returned from the call (on the call stack). This memory can be assigned to a variable and you will keep it around (the memory on the call stack will be memcpy'd into your local variable):

Node n = newNode();

However, as a Node gets more complicated, you will run into problems. For example, if you have nested data structures, these won't get copied along and could be destroyed as newNode() cleans up.

Also, as the memory required for Node gets larger (ie more fields), it will take more and more memory on the stack to make these calls. This can limit things such as recursion, or just general efficiency.

To deal with these limitations, you allocate memory on the heap in newPNode(); This always returns a pointer, regardless of the size of Node. However, you have to make sure you explicitly clean up this memory later, or you will have a memory leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM