views:

96

answers:

2

Hi everybody,

I have the problem that memcpy/memmove change the pointer of a struct FOO foo, which is neither src nor destination of the function. Here are the gdb outputs:

Before memmove(y,y_temp,size_y);:

(gdb) p y
$38 = 0xbff7a2e0
(gdb) p y_temp
$39 = (float *) 0x815ea20
(gdb) p foo
$40 = (FOO *) 0x81d4e90

and after:

(gdb) p y_temp
$41 = (float *) 0x343434
(gdb) p y 
$42 = 0x343434 
(gdb) p foo
$43 = (FOO *) 0x343434

Here are the definitions of the variables:

FOO *foo;
float y[nsamples];
float size_y = nsamples*sizeof(y);
float* y_temp = (float*) malloc(size_y);

I know, that it is not a bug with memcpy/move, so I looking for a tipp, what programming error on my side could have caused it.

Thanks

+4  A: 
size_t size_y = sizeof(y);

sizeof(y) already gives you the size of the whole array, and the type should be size_t.

If you do this, y and the memory y_temp points to will be the same size. You should also make sure you're moving in the right direction. Right now, y is the destination. Also, if the source and destination don't overlap (which they won't here), use memcpy.

Matthew Flaschen
+1, and a second time too if I could for for `size_t` advice
Binary Worrier
Thanks, I knew it was one of this small stupid bugs!
Framester
+1  A: 
float y[nsamples];
/* let's say a float is 4 bytes and nsamples is 13 */
float size_y = nsamples*sizeof(y);
/* size_y is now 13 * 52 == 676 */

and then you do

memmove(y, y_temp, size_y);

But y does not have enough space for all of size_y bytes!

pmg