memcpy/memmove 的奇怪行为

发布于 2024-09-25 05:43:13 字数 625 浏览 9 评论 0原文

我遇到的问题是 memcpy/memmove 更改了 struct FOO foo 的指针,该指针既不是函数的 src 也不是目标。以下是 gdb 输出:

memmove(y,y_temp,size_y); 之前:

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

和之后:

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

以下是变量的定义:

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

我知道,这不是 memcpy/move 的错误,所以我正在寻找提示,我这边的编程错误可能导致它。

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无妨# 2024-10-02 05:43:13
size_t size_y = sizeof(y);

sizeof(y) 已经给出了整个数组的大小,并且类型应该是 size_t

如果这样做,yy_temp 指向的内存将具有相同的大小。您还应该确保您朝着正确的方向前进。现在,y 是目的地。另外,如果源和目标不重叠(这里不会重叠),请使用memcpy。

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.

独木成林 2024-10-02 05:43:13
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 */

然后你就可以了

memmove(y, y_temp, size_y);

但是y没有足够的空间容纳所有size_y字节!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文