-1

I am writing a C program which searches for a string inside a file. When I compile and execute the program from the command line, I get the segmentation fault error. I know that this error means that I do not have access to the memory I am trying to write to, but I do not see how this is occurring in my program. Here is the segment of code in my main function where the error is occurring:

int num_of_arguments = argc;
char *filename = argv[2];
char *search_string;

strcpy(search_string, argv[1]);

int i = 0;
while (search_string[i]) {
    tolower(search_string[i]);
    i++;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
KOB
  • 4,084
  • 9
  • 44
  • 88

2 Answers2

4

In your code

 strcpy(search_string, argv[1]);

invokes undefined behavior as you're trying to to write into unitialized memory, pointed by search_string. As you've not initialized search_string explicitly, the pointer (pointer value) is indeterminate and most likely it points to some memory location that is not accessible from your program. Thus the pointer essentially points to invalid memory location.

You need to allocate memory to search_string before you can copy into it.

Otherwise, make search_string an array of sufficient length that can hold the contents of argv[1] (including null-terminator) before performing strcpy().

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Thank you, that makes perfect sense now that I think about it. As pointed out in other answers, `strdup()` is a better solution to my problem. – KOB Feb 09 '16 at 21:52
  • @CornOnTheKob well, I'm not against using `strdup()`, but just a note, it is not standard C. – Sourav Ghosh Feb 09 '16 at 22:06
0

You are using search_string without initialization, instead of:

strcpy(search_string, argv[1]);

You should use:

search_string=strdup(argv[1]);

Look: strcpy vs strdup

Community
  • 1
  • 1
  • I didn't even know `strdup` exists. I am using this isntead and all is working fine, thank you. – KOB Feb 09 '16 at 21:52