0
>>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)

Code:

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);
}

And here is createElement function

  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);
  }

Can someone tell me what I got wrong?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • Valgrind tells you what the problem is; you're reading beyond the bounds of your length-1 allocation. You should use the debugger to figure out why that is. – Oliver Charlesworth Mar 30 '13 at 11:51
  • ...and you should also [not cast the return value of `malloc()`.](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) –  Mar 30 '13 at 11:53
  • 1
    I don't think problem is in casting the return value of malloc –  Mar 30 '13 at 11:55

1 Answers1

1

I see one problem in dynamicAllocateStr.

When you copy a string you have to allocate memory for the null terminator \0 and copy it.

Note: you can simply use strdup, your platform either already supports it or you can use an implementation from here: strdup() - what does it do in C?

Community
  • 1
  • 1
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • And he is probably passing a `result->name/text` as a parameter to `createElement` again, so in the end `strlen` fails to find the terminating `\0`. – Bryan Olivier Mar 30 '13 at 12:01