1

im just starting C and i dont know why this is happening. When i excuted the program it only stored 1 value in the service_code array. For some reason, the scanf() is keeping the loop counter ias 0. I couldn't find a solution. The scanf() is causing the forloop to to run infinitely. Does anyone know how to fix this?

#include <stdio.h>
#include <string.h>

int main() {
    
char name [100];
char str [10];
int discount = 0 ;
int age;
char service_codes[4][6];


printf("Welcome to Nelson Lanka Hospital \n");
printf("Our Services : \n SV105 - Doctor Channeling \n SV156 - Pharmacy \n SV128 - Laboratory \n SV100 - OPD \n \n");

printf("Enter your Details \n Name : ");
scanf("%[^\n]",name);
printf(" Enter age : ");
scanf("%d",&age);



printf(" Enter the Sevice code for the service you need : ");
scanf("%s", str);
strcpy(service_codes[0], str);


for(int i = 1; i<4; i++){

    char yn [2] = "y";
    printf("Do you need any other sevices? (y/n) : ");
    gets(yn);
    if (strcmp(yn, "n")==0){
        break;
    }
    printf(" Enter the Sevice code for the service you need : ");
    scanf("%s", str);
    strcpy(service_codes[i], str);
    printf("%s \t %s \t %d \n",service_codes[i],str,i);

}


for (int x = 0; x<4; x++){
    printf("%s \n",service_codes[x]);
}

}

  • 3
    Does this answer your question? [scanf causing infinite loop in C](https://stackoverflow.com/questions/32849647/scanf-causing-infinite-loop-in-c) – schoche Sep 23 '20 at 07:00
  • Always check `scanf()`'s return value for errors. And never use `gets()`, the only function so bad it was removed from the standard. – Shawn Sep 23 '20 at 07:02

1 Answers1

0

For some reason, the scanf() is keeping the loop counter i as 0.

You're probably having a buffer overflow that is altering the variables in the stack (such as the variable i). I see at least two points in your program where a buffer overflow may occur:

  • scanf("%s", str);: the array str only has room for 9 characters (plus 1 end null character used as a string terminator). If you type in a string longer than 9 characters (including the newline and carriage return characters that are appended when you hit ENTER) then scanf will corrupt the stack.

  • strcpy(service_codes[i], str);: each element in the array service_codes is defined to have 6 bytes each (room for 5 characters plus 1 end null terminator). By copying a string like this, in which str may be longer than service_code, you'll run into a buffer overflow.

C is a powerful language that allows you to do anything, even shooting at your own feet. You must be careful at every line you write in your code!

Claudi
  • 5,224
  • 17
  • 30