[LCP] Realloc and null pointers
gearon at ieee.org
Wed Feb 11 11:01:46 EST 2009
On Tue, Feb 10, 2009 at 5:01 PM, Christopher Howard <choward at indicium.us> wrote:
> Let's say I declare a char pointer:
> char * label;
> Can I simply allocate memory to it like so?:
> realloc(label, 100*sizeof(char));
> Or do I need to malloc it first?
> I read in the man pages that if "label" is null, realloc will behave just
> like malloc. But is the "label" pointer null by default, or do I have to
> assign it a NULL value to be sure?
Yes. If you don't set it to something, then it will just give you a
value off the stack. Other languages clear out variables when they're
allocated, but not C.
> I'm writing memory management functions to handle the memory in some of my
> structs, so I wanted to make things as simple as possible for myself.
There isn't usually much call for realloc. If you need to allocate,
then use malloc (or calloc - though only if you need everything set to
zero, as it costs more to use). If you're reallocating, then use
realloc, but I wouldn't do this as the default, especially if you want
to keep things "simple".
More information about the linuxCprogramming