c – Valgrind complains with Invalid write of size 8

c – Valgrind complains with Invalid write of size 8

This looks wrong:

char**return_data=(char**)malloc(MAX_SOURCE_STRINGS+1);

Should probably be:

char **return_data = malloc ( (MAX_SOURCE_STRINGS+1) * sizeof *return_data );

(spaces added for convenience).

EDIT: Some additional explanation:
When you say return_data[i]=... you are trying to write something into return_data[i]. Now, return_data is char**, so return_data[i] is char*. So you are writing a pointer into some location in memory.

It looks like your pointers are 8 bytes long (which is fine), but youve only allocated 6 bytes: MAX_SOURCE_STRING+1. So there is a problem.

The fact that youre trying to write it into offset 0 doesnt matter – youre still trying to write more data than the buffer can take, and thats what valgrind is complaining about.

To solve the problem, you should allocate enough space to hold an array of pointers. Each pointer takes sizeof(char*), which can also be written as sizeof(*return_data) or sizeof *return_data. So in total you should allocate n * sizeof *return_data bytes, where n is (in your case) the magic number 6.

c – Valgrind complains with Invalid write of size 8

Leave a Reply

Your email address will not be published.