-1

Possible Duplicate:
what’s the point in malloc(0)?

Why does malloc(0) actually return a valid pointer for writing ?

char *str = NULL;

str = (char*)malloc(0); // allocate 0 bytes ?

printf("Pointer of str: %p\n", str);

strcpy(str, "A very long string ...................");

printf("Value of str: %s", str);

free(str); // Causes crash if str is too long

Output:

Pointer of str: 0xa9d010
Aborted
Value of str: A very long string ...................

When str is shorter then it just works as it should.

BTW: For compiling I used GCC with "-D_FORTIY_SOURCE=0 -fno-stack-protector"

*** glibc detected *** ..: free(): invalid next size (fast): 0x0000000000a9d010 ***
Community
  • 1
  • 1
Marco
  • 7,007
  • 2
  • 19
  • 49

3 Answers3

4

It is undefined behavior to dereference the pointer returned by malloc(0).

From the C Standard:

(C99, 7.20.3p1) "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, except that the returned pointer shall not be used to access an object."

ouah
  • 142,963
  • 15
  • 272
  • 331
2

Why does malloc(0) actually return a valid pointer for writing?

It doesn't return a valid pointer for writing. It returns a valid pointer for not using it. Or it may return NULL as well since the C standard specifies this case to be implementation defined.

  • So basically it just returns a random pointer? – Marco Jan 23 '13 at 18:59
  • 1
    @user2005038 I don't know how random it is. It returns a valid pointer, which is not to be dereferenced afterwards. –  Jan 23 '13 at 19:03
  • It's not "random": it shall not be equal to the address of any object nor any pointer returned by previous invocations of `malloc(0)`. – R.. GitHub STOP HELPING ICE Jan 23 '13 at 19:10
  • 1
    Certainly it is sensible to return a unique pointer. E.g., consider an application that is partitioning a set (e.g., here is a set of strings, make a partition for each initial character), and one of the partitions happens to contain zero objects. So it makes sense to allocate zero bytes for the contents, but the application may still want its pointer to be unique, so that it can be distinguished from the pointers to the contents of other partitions. – Eric Postpischil Jan 23 '13 at 19:39
1

malloc() is supposed to return a void* pointer. And it faithfully does that. But leads to UB when you dereference it.

sr01853
  • 6,043
  • 1
  • 19
  • 39