15

I was recently trying to track down some bugs in a program I am working on using valgrind, and one of the errors I got was:

==6866== Invalid write of size 4
==6866==    at 0x40C9E2: superneuron::read(_IO_FILE*) (superneuron.cc:414)

the offending line # 414 reads

amplitudes__[points_read] = 0x0;

and amplitudes__ is defined earlier as

uint32_t * amplitudes__ = (uint32_t* ) amplitudes;

Now obviously a uint32_t is 4 bytes long, so this is the write size, but could someone tell me why it's invalid ?

2 Answers 2

10

points_read is most likely out of bounds, you're writing past (or before) the memory you allocated for amplitudes.

4

A typical mistake new programmers do to get this warning is:

struct a *many_a;
many_a = malloc(sizeof *many_a * size + 1);

and then try to read or write to the memory at location 'size':

many_a[size] = ...;

Here the allocation should be:

many_a = malloc(sizeof *many_a * (size + 1));

Not the answer you're looking for? Browse other questions tagged or ask your own question.