Valgrind中的读取大小无效

时间:2013-03-30 11:49:50

标签: c valgrind

>>Invalid read of size 1
==9464==    at 0x4C28804: __GI_strlen (mc_replace_strmem.c:284)
==9464==    by 0x400C11: dynamicAllocateStr (in /home/xkaya/DomTree/domtree)
==9464==    by 0x400CDC: createElement (in /home/xkaya/DomTree/domtree)
==9464==    by 0x400E50: cloneNode (in /home/xkaya/DomTree/domtree)
==9464==    by 0x4006A2: main (in /home/xkaya/DomTree/domtree)
==9464==  Address 0x51c0461 is 0 bytes after a block of size 1 alloc'd
==9464==    at 0x4C26FDE: malloc (vg_replace_malloc.c:236)
==9464==    by 0x400C21: dynamicAllocateStr (in /home/xkaya/DomTree/domtree)
==9464==    by 0x400CDC: createElement (in /home/xkaya/DomTree/domtree)
==9464==    by 0x40086D: internalReadNode (in /home/xkaya/DomTree/domtree)
==9464==    by 0x4008BB: internalReadNode (in /home/xkaya/DomTree/domtree)
==9464==    by 0x4008BB: internalReadNode (in /home/xkaya/DomTree/domtree)
==9464==    by 0x400A18: internalReadDocument (in /home/xkaya/DomTree/domtree)
==9464==    by 0x400A33: readDocument (in /home/xkaya/DomTree/domtree)
==9464==    by 0x400685: main (in /home/xkaya/DomTree/domtree)

代码:

char* dynamicAllocateStr(char* string)
{
int length;
char* result;
int i;

if (string == NULL)
    return NULL;

length = strlen(string);
result = (char*)malloc(length);

for (i = 0; i <  length; i++) {
    result[i] = string[i];
}

return (result);
}

这是createElement函数

  element* createElement(const char* name, const char* text) {
element* result;

if (name == NULL)
    return NULL;

result =  (element*)malloc(sizeof(element));

if (result == NULL)
    return NULL;

result->parent = NULL;
result->nextSibling = NULL;
result->previousSibling = NULL;
result->firstChild = NULL;
result->lastChild = NULL;     
result->name = dynamicAllocateStr((char*)name);
result->text = dynamicAllocateStr((char*)text);   

return (result);
  }

有人可以告诉我我的错误吗?

1 个答案:

答案 0 :(得分:1)

我在dynamicAllocateStr中看到了一个问题。

复制字符串时,必须为空终止符\0分配内存并复制它。

注意:您只需使用strdup,您的平台已经支持它,或者您可以使用此处的实施:strdup() - what does it do in C?