Using Integer Variable as Index in scanf

2019-02-28 06:59发布

问题:

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 you not use an int variable calculation as an index in C?

int modify(pb *PhoneBook)
{
   int x;
   int iModify = 0;
   char name_num[] = {'\0'};
   print(PhoneBook);
   printf("\nWhich entry would you like to modify? ");
   scanf("%d", &iModify);
   printf("\niModify - 1: %d\n", iModify - 1);

   printf("\nModify name or number? ");
   scanf("%s", name_num);
   convert_u(name_num);
   if (strcmp(name_num, "NAME") == 0) {
      printf("\nEnter new name: ");
      scanf("%s %s", PhoneBook[iModify - 1].cFirstName, PhoneBook[iModify - 1].cLastName); //fails here
   }
   else if (strcmp(name_num, "NUMBER") == 0) {
      printf("\nEnter new number: ");
      scanf("%s", PhoneBook[iModify - 1].cNumber); //also fails here
   }
}

回答1:

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.



回答2:

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.



标签: c arrays scanf