无法确定valgrind错误的原因

时间:2019-02-16 02:24:57

标签: valgrind

当我在一段代码摘录上运行valgrind时,它告诉我我的错误在这行代码内,但我似乎无法弄清楚(如果类型为int,则为vector_size):

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 个答案:

答案 0 :(得分:-1)

当我忘记为要分配的大小加1时,通常会出现这些错误。

所以它可能来自您的calloc大小,请尝试为其加1。

您基本上正在写分配的内存。

编辑:Valgrind告诉您,您正在尝试在分配的内存之外(以及之后)写入4个字节(浮点大小)。因此,您需要再分配4个字节来存储最后一个浮点值。