0

Novice programmer learning C, I'm encountering this 'segmentation fault (core dumped)' error while trying to run a for-loop with strcmp. I have seen questions on similar issues with strcmp, but they don't seem to address my problem. Here's the program I've written.

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

int main() {
  char ftpstring[15];
  printf("\nEnter valid ftp command > ");
  fgets(ftpstring,15,stdin);

  const char* ftp[] = { "ascii", "recv", "send", "rmdir", "mkdir" , "pwd", "ls", "cd", "status", "quit" };

  for ( int i = 0; i <= 10; i++ ) {
    int comparison;
    comparison = strcmp(ftpstring, ftp[i]);
    if (comparison == 0 ) {
      printf("%s is a valid ftp command.", ftpstring);
      break;
    }
    if(i == 10) {
      printf("%s is NOT a valid ftp command.", ftpstring);
    }
  }
}

As you can see, this program tries to read user input to determine if it matches one of the predefined valid ftp commands, then return whether or not it does.

2 Answers2

1

for ( int i = 0; i <= 10; i++ ) should be for ( int i = 0; i < 10; i++ )

The ftp array contains 10 strings, so the loop should be from 0 to 9 including.

More general solution could be

for ( int i = 0; i < sizeof(ftp)/sizeof(ftp[0]); i++ )

But it is better to define a macro

#define FTP_NUM_OF_COMMANDS 10

and define the ftp array as following:

const char* ftp[FTP_NUM_OF_COMMANDS] = { "ascii", "recv", "send", "rmdir", "mkdir" , "pwd", "ls", "cd", "status", "quit" };

In this case the compiler will also verify that you don't initialize it (by mistake) with more than 10 values. The for loop will look like this:

for ( int i = 0; i < FTP_NUM_OF_COMMANDS; i++ )

Also note that the following code should be moved outside the for loop

if(i == FTP_NUM_OF_COMMANDS) {
  printf("%s is NOT a valid ftp command.", ftpstring);
}

i==FTP_NUM_OF_COMMANDS will never occur inside the loop itself, if that condition is true, the for loop should break. Make sure that you define i outside the for loop scope so it would be available after the for loop breaks.

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45
0

You are making a comparison past the end of the array: the for loop should stop at 9, while yours goes past the end of the array.

Using 10 as a "magic number" is not a good choice, either: it is much better to have the compiler compute the size for you. Finally, it is better to use index after the loop to decide if the command has been found or not:

int index = -1;
for ( int i = 0 ; i != sizeof(ftp) / sizeof(*ftp) ; i++ ) {
    if (!strcmp(ftpstring, ftp[i])) {
        index = i;
        break;
    }
}
if (index == -1) {
    printf("%s is NOT a valid ftp command.", ftpstring);
}
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523