【问题标题】:Valgrind error possibly to do with malloc in cValgrind错误可能与c中的malloc有关
【发布时间】:2016-04-11 16:44:14
【问题描述】:

我的代码有问题。我遇到了 valgrind 错误,这与 malloc 有关。我很困惑,因为我对代码的其他部分没有任何问题,这与我遇到问题的部分完全相同。我得到的错误是:

==15151==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)                                                          
==15151==    by 0x4006E2: main (additup.c:28)




struct bigInt {
      int digit;
      struct bigInt *next;
      struct bigInt *prev;
};

struct bigInt* curInt;
struct bigInt* intHead;
struct bigInt* intTail;
struct bigInt* curSum;
struct bigInt* sumHead;
struct bigInt* sumTail;

int main(){
  int addSum(int i );
  curInt = malloc(sizeof(struct bigInt));
  intHead = malloc(sizeof(struct bigInt));
  intTail = malloc(sizeof(struct bigInt));
  curSum = malloc(sizeof(struct bigInt)); // Problem: line 28
  sumHead = malloc(sizeof(struct bigInt)); //Problem: line 29
  sumTail = malloc(sizeof(struct bigInt));  //Problem: line 30
  addSum(11); //add head to sum linked list
  addSum(99);//add tail to sum linked list
  addSum(0);

int addSum(int i){ //adds sum  structure to front of linked list
  struct bigInt* x = malloc(sizeof(struct bigInt));
  if(i==11){
    x->digit=i;
    sumHead=x;
    curSum=x;
  } else {
    x->next=sumHead->next;
    sumHead->next=x;
    x->prev=sumHead;
    curSum=x;
    x->digit=i; 
  if(i==99) sumTail=x;
  }
  return 0;
}

任何帮助将不胜感激。谢谢`

【问题讨论】:

  • 使用GMPlib;不要重新发明你自己的任意精度库
  • 该错误可能存在于您未显示的某些代码中,例如addSum。还可以考虑使用gcc -Wall -Wextra -g 进行编译,甚至可能还使用-fsanitize=address
  • 顺便说一句,我们不是调试服务。
  • 错误是你的,不是来自valgrind
  • 您是否在调试器中运行了此程序,逐步检查所有相关变量的值以了解实际情况?

标签: c malloc valgrind


【解决方案1】:
 addSum(99);//add tail to sum linked list
//...
  if(i==99) sumTail=x;

这是内存泄漏。 sumTail 指向的先前 malloc 块不再可访问。 ...而其他两个方块以同样的方式丢失。

【讨论】:

  • 所以由于我 malloc 结构 x 将在 sumTail、curSum 和 sumHead 中指向,我不需要自己 malloc sumTail、curSum 和 sumHead?
  • 对。如果稍后再次分配它们,则无需先 malloc。您可以初始化为 NULL。或者只是复制数字值,而不是分配另一个结构。
  • 非常感谢。我刚刚删除了 malloc-ing sumTail、curSum 和 sumHead 行,错误消失了
猜你喜欢
  • 2017-05-12
  • 1970-01-01
  • 2014-03-25
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多