malloc()
will allocate a block of memory and return a pointer to that memory if successful, and NULL if unsuccessful. the size of the block of memory is specified by malloc
's argument, in bytes.
the sizeof
operator gives the size of its argument in bytes.
char *someString = malloc(sizeof(char) * 50)
this will allocate enough space for a 49 character string (a C-style string must be terminated by a NULL ('\0'
) character) not including the NULL character, and point someString
at that memory.
It looks like that code in your question should be malloc(sizeof(char) * 2);
, as sizeof(char) + 2
doesn't make sense.
note that sizeof(char)
is guaranteed to always equal 1 (byte) -- but the memory representation of other types (such as long) may vary between compilers.
The way that you get (un)lucky with dynamically allocated memory is if you try to read/write outside of memory you have allocated.
For example,
char *someString = malloc(10);
strcpy(someString, "Hello there, world!");
printf("%s\n", someString);
The first line allocates enough room for 9 characters, and a NULL character.
The second line attempts to copy 20 characters (19 + NULL) into that memory space. This overruns the buffer and might cause something incredibly witty, such as overwriting adjacent memory, or causing a segfault.
The third line might work, for example if there was allocated memory right beside someString, and "Hello there, world!" ran into that memory space, it might print your string plus whatever was in the next memory space. If that second space was NULL terminated, it would then stop--unless it wasn't, in which case it would wander off and eventually segfault.
This example is a pretty simple operation, yet it's so easy to go wrong. C is tricky -- be careful.