0

My program should print out "Not found" not "Segmentation fault", what's happening here?

This is my code

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

int main(void)
{
    string names[] = {"Bill", "Charlie", "Fred", "George", "Ginny", "Percy", "Ron"};

    for (int i = 0; 1 < 7; i++)
   {
      if(strcmp(names[i], "Angle") == 0 )
      {
          printf("Found\n");
          return 0;
      }
   }
   printf("Not found\n");
   return 1;
}

I complied the program with make and when I ran it, I got "Segmentation fault". So confused...

Cheatah
  • 1,825
  • 2
  • 13
  • 21
Sherri
  • 21
  • 7

1 Answers1

1

Your for loop will stop when 1 < 7 is no longer true.

1 will always be less than 7.
Your loop will never end.

In the meantime, variable i will get incremented everytime through the loop. While i has values 0 to 6, that is not a problem. But once i is value 7 and greater, then names[i] is undefined, and can reference any memory, including invalid memory.

You might get "lucky" and accessing names[7], names[8], names[9] might not segfault... but sooner or later in your infinite loop, a Segfault will occur.

To fix this problem, re-consider when your loop should stop.
I do not think it should stop when 1 < 7.
I think you should look for a different stop condition.

abelenky
  • 63,815
  • 23
  • 109
  • 159