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???
It may seem to “work” but that’s just because you got lucky. When I run your code on one compiler it “works” on a different one it crashes because of a heap corruption. Your best bet if you want to use
scanf()is to allow scanf() to allocate the memory for you:Also keep in mind that
scanf()has a return value (which tells you number of input items successfully matched and assigned) and it’s important to check that to know if it worked.While we’re at good practices, you shouldn’t typecast the return value of
malloc()Another alternative, not using
scanf(), is to usefgets()instead: