【发布时间】:2023-03-23 02:44:01
【问题描述】:
我正在开发一个数学库。
create_vector 创建一个维度为 n 的向量:(v1, v2, v3, ..., vn)
delete_vector释放内存。
struct Vector
{
unsigned int dimension;
double *components;
};
typedef struct Vector *vector_t;
vector_t create_vector(const unsigned int dimension)
{
if(!dimension)
return NULL;
vector_t vector = (vector_t)malloc(sizeof(struct Vector));
vector->dimension = dimension;
vector->components = (double *)calloc(dimension, sizeof(double));
return vector;
}
void delete_vector(vector_t *vector)
{
if(*vector == NULL)
return;
free((*vector)->components);
free(*vector);
*vector = NULL;
}
主文件:
int main()
{
vector_t vector1 = create_vector(3);
delete_vector(&vector1);
}
在主文件中,我使用了这两个函数,但是 valgrind 给了我这些警告。没有任何内存泄漏。我该如何解决?
==6906== Invalid write of size 4
==6906== at 0x108800: create_vector (in /home/mrcoder/Scrivania/GitHub/libmath/test/testvector)
==6906== by 0x10877E: main (in /home/mrcoder/Scrivania/GitHub/libmath/test/testvector)
==6906== Address 0x4b3702c is 0 bytes after a block of size 4 alloc'd
==6906== at 0x483021B: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==6906== by 0x1087DC: create_vector (in /home/mrcoder/Scrivania/GitHub/libmath/test/testvector)
==6906== by 0x10877E: main (in /home/mrcoder/Scrivania/GitHub/libmath/test/testvector)
==6906==
==6906== Invalid read of size 4
==6906== at 0x10882B: delete_vector (in /home/mrcoder/Scrivania/GitHub/libmath/test/testvector)
==6906== by 0x108790: main (in /home/mrcoder/Scrivania/GitHub/libmath/test/testvector)
==6906== Address 0x4b3702c is 0 bytes after a block of size 4 alloc'd
==6906== at 0x483021B: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==6906== by 0x1087DC: create_vector (in /home/mrcoder/Scrivania/GitHub/libmath/test/testvector)
==6906== by 0x10877E: main (in /home/mrcoder/Scrivania/GitHub/libmath/test/testvector)
==6906==
==6906==
==6906== HEAP SUMMARY:
==6906== in use at exit: 0 bytes in 0 blocks
==6906== total heap usage: 2 allocs, 2 frees, 28 bytes allocated
==6906==
==6906== All heap blocks were freed -- no leaks are possible
==6906==
==6906== For counts of detected and suppressed errors, rerun with: -v
==6906== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
【问题讨论】:
-
如果我在 valgring 下编译并执行你的程序,我没有错误/警告。请使用调试(选项 -g)编译您的程序,以查看 valgrind 发出问题的位置,即使它可能会
vector->dimension = dimension;和vector->dimension = dimension; -
不要在
typedef别名后面隐藏指针性质,例如vector_t。这样做通常会带来更多的困惑而不是帮助。 -
所以我有:libvector.h(头文件)libvector.c(库文件)main.c (主文件)我试过了,如果我在 main.c 文件中声明这些函数,则没有警告。为什么?
-
首先,我没有看到
#include声明。确保您正在调用的函数的所有正确头文件都是#include'd。其次,您没有显示您的libvector.h头文件。显示。第三,你是如何编译你的代码的?您应该打开所有警告。 -
@bruno 该示例不完整。我已经学会(主要是通过艰难的方式......)在给出不完整信息的情况下不要猜测答案,尤其是当只需询问即可轻松提供完整信息时。
标签: c memory-leaks malloc valgrind