Reputation: 93
I've written the following code :
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ch = malloc(0 * sizeof(char));
int n = 300;
sprintf(ch, "%d", n);
printf("ch is : %s", ch);
return 0;
}
I've switched the 0 in the malloc function to different numbers to experiment and I tried putting 0 meaning allocating no memory but when I run the program it worked just fine and I don't understand why is that exactly because if I put 0 it's like allocating no memory at all so what's happening here ?
Upvotes: 0
Views: 186
Reputation: 122493
malloc(0)
is implementation-defined. It may return a null pointer, see C FAQ for detail.
The problem is in the following line:
printf("ch is : %s", ch);
ch
is not a string (i.e, null-terminated char array), to print it with "%s"
is illegal.
Upvotes: 1
Reputation: 35600
C lets you shoot yourself in the foot.
The malloc docs say
If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.
So your implementation is returning something other than zero. Your sprintf is writing into memory that it "shall not" write to. But in this particular case, you got lucky, and it was nowhere critical - at least nowhere that mattered in this short test program. In a longer program with more mallocs and frees, you almost surely would run into trouble.
Upvotes: 2