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 you’ve only allocated 6 bytes: MAX_SOURCE_STRING+1. So there is a problem.

The fact that you’re trying to write it into offset 0 doesn’t matter – you’re still trying to write more data than the buffer can take, and that’s 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.

Leave a Comment