【问题标题】:Valgrind: is not stack'd, malloc'd or (recently) free'dValgrind:不是stack'd,malloc'd或(最近)free'd
【发布时间】:2016-02-02 11:19:36
【问题描述】:

我有一个结构“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)

我的内存管理有什么问题?

如果您需要更多信息,请告诉我。

【问题讨论】:

    标签: c memory-management valgrind


    【解决方案1】:

    "12345" 是一个字符串文字。它们不是“stack'd or malloc'd”,它们就像全局静态变量。您无法释放其中之一。

    正如你从你的行中看到的

    p = calloc(6, 1);
    

    您会知道在指针上使用= 意味着使指针指向右侧指向的相同对象(换句话说,p 现在保存了您分配给它的地址)。

    线

    p = "12345";
    

    也不例外,你让p停止指向calloc'd空间,并开始指向"12345"的位置。

    如果您打算从"12345" 的位置复制到p 指向的位置,您将需要使用一些取消引用运算符,或预定义的函数,例如strcpy

    【讨论】:

      【解决方案2】:

      您需要使用strcpy 将字符串复制到您的值中。现在,您正在覆盖 calloc'd 指针,该指针指向实际位于可执行二进制文件中的字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-28
        • 1970-01-01
        • 2018-10-12
        • 1970-01-01
        • 2017-01-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多