【发布时间】:2015-10-17 17:01:40
【问题描述】:
我正在编写一个包含以下循环的函数。此段从包含多行文本的文本文件中读取,每行包含一个单词和 \r\n 个字符。
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
}
有问题的行是:if( strlen(tPtr) > 0)。如果 tPtr 为 NULL,则此行会导致 seg。错误(奇怪地调用strlen(tPtr) 不会给出段错误)。
无论如何,我认为这不是问题,因为在 while 循环开始时会检查 sPtr 是否为 NULL 情况。所以很明显,在strtok(sPtr, "\r\n") 对sPtr 进行操作后,对于一些非NULL 的sPtr,你会得到NULL。但我不明白这怎么会发生。
【问题讨论】:
-
想通了:它用 \n 读取了一个空字符串,当 strtok() 返回一个空指针时。