C Warning: Function returns address of local variable

Some other answers suggest that you malloc something and return it. This is bad practice in the same sense as in C++, when you new something in a function and the caller is supposed to delete it (who has ownership?)

There is a reason that many C APIs have the format of:

function(buf, length);

Meaning that the CALLER supplies the buffer and how long it is. IT is the caller’s responsibility to allocate and de-allocate this buffer and your function should use it, and check that you’re not going to overflow the length.

Do not malloc and return. It’s just asking for trouble.

Leave a Comment