【发布时间】:2014-10-16 05:19:34
【问题描述】:
我目前正在做一个我自己的标记器的项目。我的代码可以编译并且工作正常,但是 valgrind 给出了错误:
==2572== Conditional jump or move depends on uninitialised value(s)
==2572== at 0x4C2B308: strlen (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==2572== by 0x400FCB: strdup (Lex1.c:173)
==2572== by 0x400EBA: lex (Lex1.c:140)
==2572== by 0x400A3B: main (mainLex.c:34)
==2572==
==2572== Conditional jump or move depends on uninitialised value(s)
==2572== at 0x4C2B35B: strcpy (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==2572== by 0x400FFC: strdup (Lex1.c:177)
==2572== by 0x400EBA: lex (Lex1.c:140)
lex 中的第 140 行是以下代码中的“temp->text”行:
token *head, *temp, *right, *temp1;
char *line1 = strdup(line);
char *curr = separatebetter(line1);
temp = (token *)malloc(sizeof(token));
temp->text=strdup(curr);
奇怪的是,我可以打印 curr 的值,但根据我的假设,valgrind 表示 curr 在任何时候都没有初始化,尽管我清楚地初始化了它。
valgrind 在 strdup 中引用的两行是:
int n = strlen(str) + 1;
strcpy(dup, str);
而separatebetter的相关代码是:
char *separatebetter (char *arr)
{
int status=0;
static char* perm;
if (arr!=NULL)
{
perm=arr;
}
if((perm[0]=='\0')||(perm[0]=='\n'))
{
return NULL;
}
if (strcspn(perm, "<|>&")==0)
{
status=1;
}
if (strcspn(perm, ";()")==0)
{
status=2;
}
char *toke = perm;
char *temp;
//Status is set to 1 or 2
if (status==1)
{
printf("here\n");
temp=toke;
char *temp1=malloc(strlen(temp)*sizeof(char));
temp1=temp;
char *final = malloc(3*sizeof(char));
temp1++;
if(temp[0]==temp1[0])
{
final[0]=temp[0];
final[1]=temp[0];
*temp='\0';
temp++;
*temp='\0';
perm=temp+1;
return final;
}
else
{
final[0]=temp[0];
final[1]='\0';
*temp='\0';
perm=temp+1;
return final;
}
}
else if (status==2)
{
temp=toke;
char *final = malloc(2*sizeof(char));
final[0]=temp[0];
final[1]='\0';
*temp='\0';
perm=temp+1;
return final;
}
perm[0]='\0';
return toke;
}
编辑:我试过 printf curr,虽然我得到了输出,但 valgrind 仍然告诉我
==6625== Conditional jump or move depends on uninitialised value(s)
==6625== at 0x4E7AB5B: vfprintf (in /usr/lib64/libc-2.17.so)
==6625== by 0x4E83CD8: printf (in /usr/lib64/libc-2.17.so)
==6625== by 0x400EA8: lex (Lex1.c:138)
==6625== by 0x400A3B: main (mainLex.c:34)
认为 curr 的初始化是问题,我错了吗?
【问题讨论】:
-
这是错误的:
char *curr = malloc(100*sizeof(char)); curr = separatebetter(line1);。您立即泄漏分配的内存并将curr设置为指向其他地方。temp1也会发生同样的事情。 -
显示您实际测试的代码。为了获得更好的帮助,发布 MCVE。