当我在代码的摘录上运行valgrind时,它告诉我我的错误在于这行代码,但我似乎无法弄明白(vector_size if int类型):
float *rotations = (float *) calloc(vector_size*vector_size, sizeof(float));
这是valgrind的输出:
Invalid write of size 4
==5488== at 0x109272: main (rotate_vector.c:20)
==5488== Address 0x4a47164 is 0 bytes after a block of size 196 alloc'd
==5488== at 0x4839775: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5488== by 0x1091D5: main (rotate_vector.c:8)
==5488==
==5488==
==5488== Process terminating with default action of signal 11 (SIGSEGV)
==5488== Access not within mapped region at address 0x4E47018
==5488== at 0x109272: main (rotate_vector.c:20)
==5488== If you believe this happened as a result of a stack
==5488== overflow in your program's main thread (unlikely but
==5488== possible), you can try to increase the size of the
==5488== main thread stack using the --main-stacksize= flag.
==5488== The main thread stack size used in this run was 8388608.
有关如何修复的任何建议?
当我忘记将1添加到您想要分配的大小时,我通常会遇到这些错误。
所以它可能来自你的calloc
尺寸,尝试加1。
你基本上写的是你分配的内存。
编辑:Valgrind告诉你,你正试图在你分配的内存之外(和之后)写4个字节(浮点大小)。因此,您需要再分配4个字节来存储最后一个浮点值。