Sergey Zykov Sergey Zykov - 1 month ago 21
C Question

C alternative to malloc

While reading K&R (section 6.5, second edition) I have encountered the following function:

struct tnode *talloc(void)
{
return (strcut tnode *) malloc( sizeof(strcut tnode) );
}


the function allocates some spaces to store a struct tnode. I just want to check my understanding by asking whether I would achieve the same with:

strcut tnode *talloc(void)
{
struct tnode s;
return &s;
}

Answer

The answer is no.

struct tnode *talloc(void)
{
    return (strcut tnode *) malloc( sizeof(strcut tnode) );
}

malloc allocates space which can be used afterwards, oftentimes the space is allocated on the heap. Space which is allocated with malloc needs to be free'd manually when you don't need it any more - otherwise you will get a memory leak. This pointer can be used after the function returned.

In the following example

strcut tnode *talloc(void)
{
    struct tnode s;
    return &s;
}

the struct is allocated on the stack and automatically free'd when the function exits. Thus, your returned pointer becomes a dangling pointer which you cannot use (outside the function). Using a scoped object outside its scope is undefined behavior.

Comments