c – Valgrind – Invalid write of size 1 for strcpy

c – Valgrind – Invalid write of size 1 for strcpy

You need to malloc one more byte for temp->data

temp->data = malloc(strlen(node2->data)+1);

This is because you need the final byte to store then ‘’ indicating the end of the string.

Not only do you need to add one to your malloc length, but also you can’t swap strings using strcpy like you are doing. What if the first string was malloced with 10 bytes and the second with 29 bytes? When you copy to swap, you will overrun the first string’s buffer. It would be best to swap the pointers. If data is defined as a fixed length array, then what you are doing is ok, but then temp could also be the same sized array instead of a node.

c – Valgrind – Invalid write of size 1 for strcpy

Leave a Reply

Your email address will not be published.