I was testing a c program in order to see what happens in a loop if inside a string allocated with malloc i replace \0 with any other character. What I thought it gave me as output is either segmentation fault or access to another area of memory since malloc returns a memory area of a specific number of bytes. However, I found out some strange behavior with malloc. Here is my code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void foo(char *s)
{
int i = 0;
while(s[i])
i++;
s[i++] = '5';
return ;
}
int main(int argc, char **argv)
{
char *s = malloc(4);
printf("%p\t%s\n", s, s);
strcpy(s, "test");
printf("%p\t%s\n", s, s);
foo(s);
printf("%p\t%s\n", s, s);
foo(s);
printf("%p\t%s\n", s, s);
return 0;
}
idk even if i allocate for 4 bytes in the foo function the character are added correctly in the second call of foo(). this is the output:
0x131606960
0x131606960 test
0x131606960 test5
0x131606960 test55
But then i changed the s declaration with malloc(1)
and still produce the same output, strcpy also works fine (Why this happen? shouldn't it give segmentation fault? Maybe the OS operates under the hood in this case?).
The strange behavior occurs when I replace with malloc(0)
, that, according to the specification malloc(0) have to return a NULL pointer but with the possibility to pass pointer to the free() function. Thus, it's basically the same thing as doing
char *s = NULL;
instead produce this output:
0x146704080
0x146704080 test
0x146704080 test5
0x146704080 test55
Anyone know why this happens?