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.