Using Integer Variable as Index in scanf

后端 未结 2 923
半阙折子戏
半阙折子戏 2021-01-25 02:22

I\'m trying to do the below in my function but keep getting a segmentation fault error. It\'s failing when I\'m trying to use [iModify - 1] as my index.

Can

相关标签:
2条回答
  • 2021-01-25 02:28

    You have used char name_num[] = {'\0'}; in your code. name_num has the length of 1 char, which is too short to hold a string later.

    Therefore, you are writing out-of-bounds when you read name_num.

    0 讨论(0)
  • 2021-01-25 02:31

    The problem here is

     char name_num[] = {'\0'};
    

    here, name_num is having a length of 1 char, which will not be sufficient for holding a string at a later point. So, when you do

    scanf("%s", name_num);
    

    you're essentially writing out of bound which invokes undefined behavior.

    Reference: C11, chapter §6.7.9

    If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer. [...]

    To compare with your code, name_num is an array of unknown size which is being initialized by only a single element in a brace enclosed initializer, so the size of the array will be 1.

    Solution: You have to mention the size explicitly at the time of definition. You'll be needing something like

    char name_num[32] = {'\0'};     //32 is just for example purpose
    ....
    scanf("%31s", name_num);  // make sure longer inputs don't blow up the buffer
    

    or similar.


    Having said that, please notice your int modify() function does not return any value. If the returned value is used in the caller, it will again invoke undefined behavior.

    0 讨论(0)
提交回复
热议问题