使用strcat时出现未初始化值依赖的条件跳转/移动问题求助
问题分析与修复
Valgrind 报错的核心原因是:调用 strcat 时,目标字符串 text 未初始化为以 \0 结尾的有效字符串。首次分配 text 时(此时 text 为 NULL,realloc 等价于 malloc),分配的内存处于未初始化状态,strcat 会在这块内存中寻找 \0 来确定追加位置,从而读取未初始化的值,触发 Valgrind 的"Conditional jump or move depends on uninitialised value(s)"错误。
修复方案
在首次向 text 添加内容时,使用 strcpy 替代 strcat(strcpy 不需要目标字符串预先以 \0 结尾);后续追加内容时再使用 strcat。以下是修正后的核心代码片段:
while(fscanf(fi, "%[^\n]\n", str) != EOF) { word = strtok(str, " \n"); while(word != NULL) { if((number > 1) && correct) { size_t word_len = strlen(word); if (text == NULL) { // 首次分配内存,直接复制单词 len_text = word_len; text = malloc((len_text + 1) * sizeof(char)); strcpy(text, word); } else { // 追加单词到已有字符串 len_text += word_len; text = realloc(text, (len_text + 1) * sizeof(char)); strcat(text, word); } // 添加空格(保留原逻辑) len_text++; text = realloc(text, (len_text + 1) * sizeof(char)); strcat(text, " "); } word = strtok(NULL, " \n"); number++; } // 后续逻辑不变... }
额外优化建议
- 检查内存分配结果:
malloc和realloc可能返回 NULL,需添加错误处理,避免程序崩溃。 - 简化冗余判断:原代码中
if(len_text)检查在首次添加单词后必然为真(len_text至少为单词长度),可直接移除判断。 - 减少重复计算:将
strlen(word)的结果存入局部变量,避免重复调用。
内容的提问来源于stack exchange,提问作者Mikael Freid
相关产品推荐
相关产品推荐

