1

Possible Duplicate:
what's the point in malloc(0)?
what does malloc(0) return?

this code displays "unsuccesful" but if you replace -1 with 0 it wont be NULL. I don't get how you can allocate 0 memory space. I know there's no use but isn't NULL == 0L so it should be == 0 too..

#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
if((ptr = malloc(-1)) == NULL)
    printf("unsuccessful: no memory space was allocated.\n");
else{
    printf("successful: memoryspace was allocated. \n");
    free(ptr);
}
getch();
return 0;

}
Community
  • 1
  • 1
jantristanmilan
  • 4,188
  • 14
  • 53
  • 69
  • When `malloc` fails by returning `NULL` it should set `errno` and you should print `strerror(errno)` – Basile Starynkevitch Sep 09 '12 at 07:24
  • 2
    "I don't get how you can allocate 0 memory space" - just don't call malloc() !! – Mitch Wheat Sep 09 '12 at 07:25
  • Yeah, I was leaning towards multiple possibilities of allocating something (or maybe nothing) with one way of cleaning up. No need to check if `malloc` was called. It makes a bit more sense looking at it from a C++ class point of view, but I suppose it could happen in C. – chris Sep 09 '12 at 07:26
  • not that im gonna use it. its a "what if" question. – jantristanmilan Sep 09 '12 at 07:32
  • *NULL == 0L* Not necessarily, no. In C (not C++) NULL is typed as a pointer with the value of zero `(void *)(0)`, so don't fall into the trap of equating NULL with zero in all cases. – cdarke Sep 09 '12 at 07:35

1 Answers1

12

It's implementation-defined:

7.22.3-1

If the space cannot be allocated, a null pointer is returned. 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.

So it can return NULL but it doesn't have to. Also, to clarify why malloc(-1) fails, notice its prototype is:

void *malloc(size_t size);
             ^^^^^^

So you're converting -1 to an unsigned type, yielding a very large value.

cnicutar
  • 178,505
  • 25
  • 365
  • 392