开发者

Strange behavior of memcpy/memmove

开发者 https://www.devze.com 2023-01-17 13:58 出处:网络
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:

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 variable开发者_StackOverflow社区s:

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


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.


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消