malloc and scanf string

核能气质少年 提交于 2020-01-21 10:26:33

问题


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???


回答1:


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:

scanf("%ms", &name); // compiled with -std=c99 this will allocate the correct amount
                    // of memory for you. You can use "%as" if you're using -std=c89 

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 use fgets() instead:

fgets( name, SZSTRING, stdin);



回答2:


No it doesnt. But exceeding an allocated buffer's size does not always lead immediatly to a segmentation fault. Sometimes areas get corrupted and the effect will show later or even never.




回答3:


It's possible that such cases will run without segfault. In this case its just that you are using a space that you haven't claimed, corrupting some memory locations which might are owned by "somebody" else.



来源:https://stackoverflow.com/questions/14500880/malloc-and-scanf-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!