我正在尝试执行一个函数,从注释中清除给定的代码。代码工作得很好,但是valgrind不喜欢它。输入包含应该清除的代码,我正在尝试将已清除的代码保存到新代码中。我用malloc尝试过不同的价值观,但valgrind似乎不喜欢它。我的代码如下所示:
char *remove_comments(char *input)
{
int a=0;
char *newcode=malloc((strlen(input))*sizeof(char));
int c=0;
while (a<strlen(input)){
if((*(input+a)=='/') && (*(input+a+1) =='/')){
while(*(input+a)!='\n'){
a++;
}
a++;
}
if(*(input+a)=='/' && *(input+a+1)=='*'){
int b=1;
while(b!=0){
a++;
if(*(input+a)=='*' && *(input+a+1)=='/'){
b--;
}
}
a++;
a++;
}
*(newcode+c)=*(input+a);
a++;
c++;
}
free(input);
return newcode;
}瓦兰的输出是这样的:
==30337== Conditional jump or move depends on uninitialised value(s)
==30337== at 0x402E50: mycompare_new (checkhelp.c:86)
==30337== by 0x401F23: test_remove_comments (test_source.c:81)
==30337== by 0x406FD2: srunner_run (in /tmp/user/ee67882dc0b6fb0b4d921c48de81577a5d87cccdc65e0a1580d6726d197a5e87/c-kurssi/Module_3/08_polisher/test/test)
==30337== by 0x402512: tmc_run_tests (tmc-check.c:134)
==30337== by 0x4021A7: main (test_source.c:206)
==30337== Uninitialised value was created by a heap allocation
==30337== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==30337== by 0x402FF1: remove_comments (source.c.nomain.c:18)
==30337== by 0x401EBD: test_remove_comments (test_source.c:74)
==30337== by 0x406FD2: srunner_run (in /tmp/user/ee67882dc0b6fb0b4d921c48de81577a5d87cccdc65e0a1580d6726d197a5e87/c-kurssi/Module_3/08_polisher/test/test)
==30337== by 0x402512: tmc_run_tests (tmc-check.c:134)
==30337== by 0x4021A7: main (test_source.c:206)
==30337==
==30337== Conditional jump or move depends on uninitialised value(s)
==30337== at 0x402E50: mycompare_new (checkhelp.c:86)
==30337== by 0x4020BA: test_remove_comments (test_source.c:109)
==30337== by 0x406FD2: srunner_run (in /tmp/user/ee67882dc0b6fb0b4d921c48de81577a5d87cccdc65e0a1580d6726d197a5e87/c-kurssi/Module_3/08_polisher/test/test)
==30337== by 0x402512: tmc_run_tests (tmc-check.c:134)
==30337== by 0x4021A7: main (test_source.c:206)
==30337== Uninitialised value was created by a heap allocation
==30337== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==30337== by 0x402FF1: remove_comments (source.c.nomain.c:18)
==30337== by 0x402045: test_remove_comments (test_source.c:102)
==30337== by 0x406FD2: srunner_run (in /tmp/user/ee67882dc0b6fb0b4d921c48de81577a5d87cccdc65e0a1580d6726d197a5e87/c-kurssi/Module_3/08_polisher/test/test)
==30337== by 0x402512: tmc_run_tests (tmc-check.c:134)
==30337== by 0x4021A7: main (test_source.c:206)
==30337== 发布于 2017-02-20 19:34:39
这段代码有很多问题。
strlen(input)+1。a与strlen(input)进行比较,这意味着您正在重新计算所看到的每个字符的输入长度。计算它一次,并将其保存在一个变量中,或者只循环while (!input[a]),这将导致它在输入末尾到达NUL时停止循环。*(input+a)语法;使用input[a]。我猜想,您在测试中得到了val研错误,因为您正在使用返回的字符串执行strcmp,而且由于它不是以NUL结尾的,所以strcmp正在游走到未初始化的堆内存中。
https://stackoverflow.com/questions/42352745
复制相似问题