gpt4 book ai didi

c - 为什么 Valgrind 报告 "Invalid read of size 2"?

转载 作者:行者123 更新时间:2023-12-04 09:42:10 25 4
gpt4 key购买 nike

struct item
{
int a;
};
int main()
{
item *a = (item *)malloc(sizeof(item));
item *b = (item *)malloc(sizeof(item));
short *c = (short *)b;
c += 3;
memcpy(a, c, sizeof(int));
free(a);
free(b);
return 0;
}

为什么 valgrind 回声“大小 2 的无效读取”?我觉得应该是4号。

来自 Valgrind 的示例消息:
==19134== Invalid read of size 2
==19134== at 0x4C2F7E0: memcpy@@GLIBC_2.14 (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==19134== by 0x400625: main (main.cpp:19)
==19134== Address 0x51fd096 is 2 bytes after a block of size 4 alloc'd
==19134== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==19134== by 0x4005FC: main (main.cpp:16)

最佳答案

我在尝试 malloc() 时遇到了“大小为 2 的无效读取” 2x2 单 channel 纹理(4 字节/uint8_t s)。我认为分配太小 - 有问题的体系结构上的字大小是 8 字节(64 位) - 所以我将分配增加了一倍,它停止了 valgrind 的提示。自 malloc()应该是对齐的,我对此感到有点惊讶(我相信这对专家来说是显而易见的),但也许它会帮助其他人。没有义务使用额外分配的空间,它只需要在那里。

...即使它没有带来洞察力,它也是一个修复。问题发生在 gcc 4.9.1(Ubuntu 4.9.1-16ubuntu6)。

关于c - 为什么 Valgrind 报告 "Invalid read of size 2"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26600704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com