A simple program below with malloc and scanf with %s to get a string as below, gives me an output I cannot comprehend. While I have 'malloced' only 5 bytes, my input string has exceeded the above size but no segmentation fault. Is scanf overiding malloc allocation?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char * name;
int SZSTRING;
printf("Enter size of name :");
scanf("%d", &SZSTRING);
name = (char*) malloc ((SZSTRING + 1) * sizeof(char));
printf("Enter name :");
scanf("%s", name);
printf("len of 'name' : %d\n",strlen(name));
printf("name final: \"%s\"\n",name);
free(name);
return 0;
}
Output:
OptiPlex-380:~/gsa/compile$ gcc -o try try.c
OptiPlex-380:~/gsa/compile$ ./try
Enter size of name :4
Enter name :qwertyui
len of 'name' : 8
name final: "qwertyui"
I noticed one more thing here: with
//scanf("%s", name);
output shows
len of 'name'= 0
and 'malloced' locations were actually memset to NULL. But its calloc and not malloc which initialises the allocated bytes to 0 as per man-page???