我有一个结构"图灵"一组"断点"巫婆里面有一个炭阵。
当我打电话给calloc
时machine.breakpoints_[free_counter].type_ = calloc(6, sizeof(char));
并且不做任何事情valgrind在我释放它时不会抱怨。
但是当我为变量赋值时,例如:
machine.breakpoints_[free_counter].type_ = "12345";
当我在这个变量上使用free时,valgrind会引发错误。
的Structs:
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)
我的记忆管理有什么问题?
如果您需要进一步的信息,请告诉我。
答案 0 :(得分:3)
您需要使用strcpy
将字符串复制到您的值中。现在,您正在覆盖calloc
指向实际上在可执行二进制文件中的字符串的指针。
答案 1 :(得分:2)
"12345"
是一个字符串文字。它们不是“stack'd或malloc'd”,它们就像全局静态变量。你无法释放其中一个。
正如您从行中看到的那样
p = calloc(6, 1);
你会知道在指针上使用=
意味着使指针指向右手所指向的相同的东西(换句话说,p
现在保存你指定给的地址它)。
该行
p = "12345";
没有什么不同,您使p
停止指向calloc'd空格,并开始指向"12345"
的位置。
如果您打算从"12345"
的位置复制到p
指向的位置,您将需要使用一些解除引用运算符或预定义函数,例如{{1 }}