0

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 ?

AALC
  • 93
  • 1
  • 2
  • 6
  • 1
    It's undefined behaviour, so you mainly got lucky. Here's an explanation: http://stackoverflow.com/questions/2022335/whats-the-point-in-malloc0 – Timo Geusch Aug 26 '14 at 01:25
  • If you allocate zero bytes, `malloc` may return a valid pointer ***or*** it may return `NULL`. You still need to check for that. – Some programmer dude Aug 26 '14 at 01:26

2 Answers2

2

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.

AShelly
  • 34,686
  • 15
  • 91
  • 152
1

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • So how would you print it ? – AALC Aug 26 '14 at 01:30
  • But if I make it a char pointer doesn't it make it a string ? Then why would I make a char pointer and not an integer pointer for example ? – AALC Aug 26 '14 at 01:42
  • 1
    @AALC It's either a null pointer, nor a pointer to `0` sized memory. Either way, there's no way or no place for a legal string (at least one byte for `'\0'`). – Yu Hao Aug 26 '14 at 01:45
  • The printf statement would be correct, assuming you had allocated enough space for the string representation of `n`, in this case 3 chars + a NULL. – AShelly Aug 26 '14 at 12:15
  • @AShelly Sure it's correct **if** the space is enough. But that's not the case here. – Yu Hao Aug 26 '14 at 12:19