的valgrind的strstr错误 [英] strstr valgrind error
问题描述
我需要一些帮助与的char *
初始化和的strstr
在C.这是普遍的问题:
I need some help with char*
initialization and strstr
in C. This is the general issue:
我有一个函数 FUNC1
func1的()FUNC2();
func1() func2();
问题是,Valgrind的给出了一个错误基本上说,可能的strstr使用未初始化值。为了改善这种情况,我不得不做一些像的char *海峡=Hello World的;
,但我不能的realloc
,这是一个问题。
The issue is that valgrind gives an error basically saying that strstr might be using an uninitialized value. To rectify this, I'd have to do something like char* str = "hello world";
, but then I can't realloc
, which is an issue.
我已经测试我的程序随机字符串和问题是Valgrind是治疗的事实 STR
为未初始化的,但我只是不知道如何在不进行初始化摆脱以realloc的能力。有什么建议么?
I have tested my program with random strings and the issue is the fact that valgrind is treating str
as uninitialized, but I just don't know how to initialize it without getting rid of the ability to realloc. Any suggestions?
该错误是:
==14356== Conditional jump or move depends on uninitialised value(s)
==14356== at 0x4C29313: strstr (in path)
==14356== by 0x401983: func2 (in path)
==14356== by 0x401B06: func1 (in path)
==14356== by 0x4013D7: main (in path)
==14356==
==14358== Syscall param execve(argv[i]) points to uninitialised byte(s)
at 0x4ECFCB7: execve (in path)
==14308== by 0x4E6A76C: do_system (in path)
==14308== by 0x4013ED: main
编辑:增加了在实际的功能,改变了名字和这样的。
Edited: Added in the actual functions, changed names and such.
推荐答案
我相信这是你的问题:
在FUNC2:
str = realloc(str, (stringLen + pathLen+1)*sizeof(char));
memmove(&str[rplcIndx + pathLen], &str[rplcIndx+2], stringLen-rplcIndx-2);
memcpy(&str[rplcIndx], path, pathLen);
的 memmove与
不会复制空终止符(这是在位置 stringLen
,但复制的最后一个字节将 rpcIndx + 2 + stringLen-rpcIndx-2-1 = stringLen-1
(记得 SRC [LEN]
是第一个字节不被复制)。这意味着
The memmove
doesn't copy the null terminator (it is at position stringLen
, but the last byte copied would be rpcIndx+2+stringLen-rpcIndx-2-1 = stringLen-1
(remember src[len]
is the first byte NOT copied). This means
- 空终止的位置没有初始化
- 的字符串可能非正常终止
顺便说一句,如果可以的话,使用 asprintf
是安全,方便和防呆做许多字符串处理任务的方式,虽然它可能会有点不太有效。
BTW, if you can, using asprintf
is safe, easy and fool-proof way of doing many string-manipulation tasks, although it may be a little less effective.
这篇关于的valgrind的strstr错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!