【问题标题】:Conditional checking on strlen(NULL) gives segmentation fault对 strlen(NULL) 进行条件检查会导致分段错误
【发布时间】: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) &gt; 0)。如果 tPtr 为 NULL,则此行会导致 seg。错误(奇怪地调用strlen(tPtr) 不会给出段错误)。

无论如何,我认为这不是问题,因为在 while 循环开始时会检查 sPtr 是否为 NULL 情况。所以很明显,在strtok(sPtr, "\r\n") 对sPtr 进行操作后,对于一些非NULL 的sPtr,你会得到NULL。但我不明白这怎么会发生。

【问题讨论】:

标签: segmentation-fault


【解决方案1】:

这是正常行为。访问 NULL 指针是正式的未定义行为,这意味着任何事情都可能发生。分段错误只是那些可能的未定义行为之一。

如果找不到您要搜索的令牌,strtok 也会返回一个 NULL 指针,这就是为什么在您的代码中检查 NULL 后仍会出现段错误的原因。 See the documentation.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-05
    • 2018-10-19
    • 2022-06-12
    • 2020-07-19
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多