0

I'm writing a function that contains the following loop. This segment reads from a text file that contains multiple lines of text, each of which contain a single word and the \r\n characters.

int strSize = 100;
char* sPtr = (char*)malloc(strSize*sizeof(char));
char* tPtr = (char*)malloc(strSize*sizeof(char)); 
FILE* fp = fopen("someTextFile.txt","r"); 

fgets(sPtr, strSize, fp); //Read in first line  

while(sPtr != NULL) {
   tPtr = strtok(sPtr, "\r\n"); //There's one word per line, which terminates with \r\n
   if( strlen(tPtr) > 0)
   {
     ... Do stuff
   }
   sPtr = fgets(sPtr, strSize, fp); //Read next line, if fgets() reaches EOF, then sPtr <= NULL
}

The problematic line is: if( strlen(tPtr) > 0). If tPtr is NULL, then this line causes a seg. fault (strangely calling strlen(tPtr) doesn't give a seg fault).

Anyways, I thought this wouldn't be a problem since sPtr gets checked at the beginning of the while loop for the NULL-case. So evidently, after strtok(sPtr, "\r\n") operates on sPtr, for some non-NULL sPtr, you get NULL. But I don't see how this can happen.

Minh Tran
  • 494
  • 7
  • 17
  • Possible duplicate of [Definitive List of Common Reasons for Segmentation Faults](http://stackoverflow.com/questions/33047452/definitive-list-of-common-reasons-for-segmentation-faults) – CodeMouse92 Oct 17 '15 at 17:37
  • Figured it out: it read an empty string with \n, which when strtok() returned a null pointer. – Minh Tran Oct 17 '15 at 18:18

1 Answers1

1

This is normal behavior. Accessing a NULL pointer is officially undefined behvaior, meaning that anything and everything might happen. A segmentation fault is just one of those possible undefined behaviors.

A NULL pointer is also returned by strtok if the token you're searching for is not found, which is why you continue to get a segfault after checking for NULL in your code. See the documentation.

CodeMouse92
  • 6,840
  • 14
  • 73
  • 130