33

Since I had read realloc will act as malloc if the size pointed is 0, I was using it without malloc(), provided the pointer was static, global, or explicitly set to NULL if automatic.

However, I notice a lot of programmers try to set it or set it to malloc(1). Is it needed?

j riv
  • 3,593
  • 6
  • 39
  • 54

2 Answers2

36

From Open Groups' specifications:

If ptr is a null pointer, realloc() shall be equivalent to malloc() for the specified size.

If ptr does not match a pointer returned earlier by calloc(), malloc(), or realloc() or if the space has previously been deallocated by a call to free() or realloc(), the behavior is undefined.

Simone
  • 11,655
  • 1
  • 30
  • 43
14

malloc is not required, you can use realloc only.

malloc(n) is equivalent to realloc(NULL, n).

However, it is often clearer to use malloc instead of special semantics of realloc. It's not a matter of what works, but not confusing people reading the code.

(Edit: removed mention of realloc acting as free, since it's not standard C. See comments.)

  • 3
    Be aware that the C99 standard for realloc with size 0 differs slightly from the POSIX standard. The C99 standard says just this: *If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value*. – JeremyP Dec 16 '10 at 09:57
  • So can one do "p = malloc(n)" followed by "realloc(p, 0)" when p is not NULL? I wouldn't really do it! Sorry about the formatting – dubnde Dec 16 '10 at 10:37
  • Jeremy, isn't that related to 'requested' size? What does it have to do with reallocation of the previous pointer? – j riv Dec 16 '10 at 10:52
  • 2
    `realloc(p,0)` is unfortunately not equivalent to `free(p)`. Both plain C and POSIX allow implementations which return a new pointer to an area you're not allowed to write to (it has "length 0") in place of `NULL`. Sadly glibc is one such implementation, and there's no shortage of buggy programs which expect the glibc behavior and use these massively-wasteful "size 0" allocations (which take at least 16 bytes each) for their own bookkeeping. – R.. GitHub STOP HELPING ICE Dec 16 '10 at 16:44
  • @R., interesting, you're right. I only checked the Linux manpage for `realloc`, not the C standard. The standard does not imply anything about `realloc` being able to free memory. I'll edit my answer accordingly. –  Dec 18 '10 at 15:35