我有一个带有“断点”数组的结构“Turing”,里面有一个 char 数组。
当我调用 calloc 时
machine.breakpoints_[free_counter].type_ = calloc(6, sizeof(char));
什么也不做,当我释放它时,valgrind 不会提示。
但是当我给变量赋值时,例如:
machine.breakpoints_[free_counter].type_ = "12345";
当我在此变量上使用 free 时,valgrind 会引发错误。
结构:
typedef struct _Breakpoint_
{
char value_;
char* type_;
} Breakpoint;
typedef struct _Turing_
{
char* band_;
int head_position_;
int start_state_;
int current_rule_;
int current_state_;
int rules_count_;
Rules* rules_;
Breakpoint* breakpoints_;
int breakpoint_counter_;
Boolean turing_over_;
} Turing;
主要内容:
int main(int argc, char *argv[])
{
Turing machine = {NULL, 0, 0, 0, 0, 0, NULL, NULL, 0, FALSE};
machine.breakpoints_ = calloc(50, sizeof(Breakpoint));
if(!machine.breakpoints_)
{
free(machine.breakpoints_);
machine.breakpoints_ = NULL;
printf(OUT_OF_MEMORY);
return ERROR_CODE_OUT_OF_MEMORY;
}
int free_counter = 0;
machine.breakpoints_[free_counter].type_ = calloc(6, sizeof(char));
machine.breakpoints_[free_counter].type_ = "12345";
machine.breakpoint_counter_++;
for (; free_counter < machine.breakpoint_counter_; free_counter++)
{
free(machine.breakpoints_[free_counter].type_); //line 133
machine.breakpoints_[free_counter].type_ = NULL;
}
free(machine.breakpoints_);
machine.breakpoints_ = NULL;
}
Valgrind 给我这个错误:
==16989== Invalid free() / delete / delete[] / realloc()
==16989== at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==16989== by 0x400A95: main (assb.c:133)
==16989== Address 0x401b18 is not stack'd, malloc'd or (recently) free'd
和:
==16989== HEAP SUMMARY:
==16989== in use at exit: 6 bytes in 1 blocks
==16989== total heap usage: 2 allocs, 2 frees, 806 bytes allocated
==16989==
==16989== 6 bytes in 1 blocks are definitely lost in loss record 1 of 1
==16989== at 0x4C2CC70: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==16989== by 0x400A50: main (assb.c:127)
我的内存管理有什么问题?
如果您需要更多信息,请告诉我。
最佳答案
"12345"
是一个字符串文字。它们不是“堆栈或 malloc”,它们就像全局静态变量。您不能释放其中之一。
正如你从你的台词中看到的
p = calloc(6, 1);
你会知道,在指针上使用 =
意味着使指针指向与右侧指向的同一事物(换句话说,现在是 p
保存您分配给它的地址)。
线
p = "12345";
也不异常(exception),您正在让 p
停止指向调用的空间,并开始指向 “12345”
的位置。
如果您打算从 "12345"
的位置复制到 p
指向的位置,您将需要使用一些取消引用运算符,或者预定义函数,例如 strcpy
。
关于c - Valgrind:不是堆叠的、malloc 的或(最近)free 的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35144164/