gpt4 book ai didi

valgrind 中的条件跳转或移动错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:43 26 4
gpt4 key购买 nike

我正在尝试使用 valgrind 来检测内存错误。这是我的代码的一部分-

else
{
137. printf("HELlo\n");
138. char * lexeme1;char * lexeme2;
139. lexeme1=substr1(bufferOld,beginPointer,sizeBuffer-1);
140. lexeme2=substr1(buffer,0,indexStart-1);
141. strcat(lexeme,lexeme1);
142. strcat(lexeme,lexeme2);
}

Token getNextToken( int fp1, FILE * fp)
{
...
207. lexeme=(char *)malloc(sizeof(char) * 100);
...
}

运行 valgrind 时出现以下错误-

==9720== Conditional jump or move depends on uninitialised value(s)
==9720== at 0x4C2DD9A: strcat (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9720== by 0x401048: updateToken (lexer.c:141)
==9720== by 0x402A92: getNextToken (lexer.c:498)
==9720== by 0x400A17: main (driver.c:66)
==9720== Uninitialised value was created by a heap allocation
==9720== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9720== by 0x4012C6: getNextToken (lexer.c:207)
==9720== by 0x400A17: main (driver.c:66)
==9720==

我不确定为什么会收到这些类型的错误。任何帮助将不胜感激。

更新-

这是我的 substr1 函数-

char * substr1(char * source,int start,int end)
{

char * dest=malloc((end-start+2)*sizeof(char));
if(end==-1)
return dest;
int i,count=0;
for(i=start;i<=end;i++)
dest[count++]=source[i];
dest[count]='\0';
return dest;
}

最佳答案

这两行

  strcat(lexeme,lexeme1);
strcat(lexeme,lexeme2);

连接到 lexeme,后者又指向未初始化的内存,分配在这里:

  lexeme=(char *)malloc(sizeof(char) * 100);

要解决此问题,请通过调用显式初始化内存:

  memset(lexeme, 0, 100);

或隐式地使用 calloc() 而不是 malloc():

  lexeme = calloc(100, 1);

更新:

第三个选项,如 Michihis comment 中提到的,将通过调用 strcpy() 替换对 strcat() 的第一次调用

  strcpy(lexeme, lexeme1);
strcat(lexeme, lexeme2);

这可能是成本最低的解决方案,至少在速度方面是这样。


在任何情况下,删除对 (char*) 的无用转换,并将 sizeof char 替换为 1,这是根据定义。

关于valgrind 中的条件跳转或移动错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36163306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com