为什么malloc在有足够内存的情况下返回NULL并始终在同一点?

时间:2012-11-17 22:23:48

标签: c memory null malloc heap

我对一个错误非常绝望,我无法克服。

对于我在大学的C编程课程,我必须为GML(图形建模语言)输入流实现解析器。

成功时,解析器将一个Abstract数据类型返回给调用者,调用者是一个Adjacency Matrix作为图表的表示。

好的,解析器工作完美无缺,在过去的几天里不会出现让我绝望的问题。在解析器中,有一个函数调用,它又调用malloc。在扫描程序中,逐个符号地向解析器传递malloc。但是,在离开扫描程序之前,通过调用free()来释放malloc'd mem块。

但是在解析器中有一个致命的函数调用,它反过来调用一个函数,该函数使用malloc来保存12个字节的内存(三个整数属性)来保存结构。需要结构来存储有关图中单个边的信息(源节点,目标节点,权重)。

这次通话是两次。第一次,一切顺利。然后,由于根据gml语法可能出现1到n个边,因此代码进入while循环,其中为同一指针分配指向新Edge Struct的指针,只要在输入流中找到Edges即可。循环中第一次调用边缘识别例程,总共第二次调用(第一个在进入循环之前发生,见m.a.),malloc返回NULL时不断失败。

我根本不知道为什么。

它不是关于内存不足的问题,因为当我在该程序的main()函数中使用malloc 1000字节时,只是为了好玩,它运行正常。

我使用Code :: Blocks和DevCPP作为IDE。在这两个程序中,程序遇到了同样的问题。

这是我的主要解析例程:

DirectedGraph Graph(char* sourceString, int*currentPosition){

 int sym;
 int restartPosition = 0;
 int* backupPosition;
 char* backupString;
 int nodeCount = 0;

 int currentSrc = -1;
 int currentTgt = -1;
 int currentWgt = -1;
 EdgeDescription e;
 DirectedGraph correctMatrix;
 MatrixStruct* errorMatrix = NULL;

 /*begin parsing*/
 bool isGraphHeader = GraphHdr(sourceString, currentPosition);

 if(isGraphHeader == true){

  bool isNode = Node(sourceString, currentPosition);

  if(isNode == true){

     while(isNode == true){

        nodeCount++;
        restartPosition = *currentPosition;
        isNode = Node(sourceString, currentPosition);

     }

     *currentPosition = restartPosition;

     /*now get edge information (from-to-weight)*/
     /*as we have already read the next symbol, we have to reset*/
     /*our read position by one symbol backwards*/
     e = Edge(sourceString, &restartPosition);  /*<======== HERE I CALL THE FATAL ROUTINE FOR THE FIRST TIME - EVERYTHING´s JUST FINE, PROGRAM PROCEEDS*/
     restartPosition = 0;

     /*just for clearer coding in if statement*/
     currentSrc = e->source;
     currentTgt = e->target;
     currentWgt = e->weight;
     destroyEdge(e);

     if(currentSrc != -1 && currentTgt != -1 && currentWgt != -1){

        /*initialize matrix with counted number of nodes*/
        correctMatrix = CreateNewGraph(nodeCount);

        /*the edge is inserted only when it lies within the boundaries*/
        /*of our graph. but we do not interrupt the whole processing, we just skip it.*/
        while(currentSrc != -1 && currentTgt != -1 && currentWgt != -1){

           if(currentSrc <= nodeCount && currentTgt <= nodeCount){

              InsertEdge(correctMatrix, currentSrc, currentTgt, currentWgt);
              restartPosition = *currentPosition;
           }

           e = Edge(sourceString, currentPosition); /* <============== THIS IS THE CALL THAT FAILS*/
           currentSrc = e->source;
           currentTgt = e->target;
           currentWgt = e->weight;

        }

        /*as we have read over the next symbol in the loop, reset the position to read*/
        *currentPosition = *currentPosition - 1;
        sym = GetNextSymbol(sourceString,currentPosition);

        if(sym == rightBrace){

           sym = GetNextSymbol(sourceString, currentPosition);

           if(sym == eot){

              return correctMatrix;
           }
           else{
              return errorMatrix;
           }
        }
        else{
           return errorMatrix;
        }
     }
     else{
        return errorMatrix;
     }
  }
  else{
     return errorMatrix;
  }
 }
 else{
    return errorMatrix;
 }

}

这里是GetNextSymbol(将符号传递给解析器的扫描程序):

/**
* DOCUMENTATION
* ============================
* This is the main scanning function
* which is used by the parser to recognize
* terminal symbols and valid literals.
*
* RETURNS: the enum code for the recognized symbol.
* or an error code, when invalid symbol encountered.
*/

int GetNextSymbol(char* sourceString, int* currentPosition){


   int symbolCode;
   int loopCounter = 0;
   char* currentIdentifier = (char*)malloc(10);
   char* currentNumber = (char*)malloc(10);
   int identifierPosition = 0;
   int numberPos = 0;
   int numericVal = 0;
   char currentChar;

   currentChar = getNextChar(sourceString, currentPosition);

    /*skip all blanks, empty chars,
    linefeeds, carriage returns*/
   while(currentChar == ' '
         || currentChar == 11
         || currentChar == 10
         || currentChar == 13
         || currentChar == '\t')
   {
      currentChar = getNextChar(sourceString, currentPosition);
   }

   /*=====================================*/
   /*Section 1: scan for terminal symbols */
   /*====================================*/

   if(currentChar == '['){
      symbolCode = leftBrace;
   }
   else if(currentChar == ']'){
      symbolCode = rightBrace;
   }

   /*=====================================*/
   /*Section 2: scan for valid literals  */
   /*====================================*/

   else if(isdigit(currentChar)){

      /*here we calculate the numeric value of a number expression*/
      /*when calculated, we assign the numeric value to the symCode variable*/
      /*this works out because the values for a real symbol are always negative*/
      symbolCode = digit;
      while(isdigit(currentChar)){

         currentNumber[numberPos] = currentChar;
         currentChar = getNextChar(sourceString, currentPosition);
         loopCounter++;
         numberPos++;
      }

      currentNumber[numberPos] = '\0';
      numericVal = atoi(currentNumber);
      symbolCode = numericVal;

      /*when identifier or braces follow number without space: reset currentPos*/
      /*to the position of the previous char*/
      if(isalpha(currentChar)){
         *currentPosition = *currentPosition - loopCounter;
      }
      else if(currentChar == ']'){
         *currentPosition = *currentPosition - loopCounter;
      }
      else if(currentChar == '['){
         *currentPosition = *currentPosition - loopCounter;
      }

   }
   else if(isalpha(currentChar)){

      while(isalpha(currentChar)){

         currentIdentifier[identifierPosition] = currentChar;
         currentChar = getNextChar(sourceString, currentPosition);
         loopCounter++;
         identifierPosition++;
      }

      /*check wether we have found a valid identifying label*/
      /*and deallocate the reserved mem space*/
      currentIdentifier[identifierPosition] = '\0';
      symbolCode = recognizeIdentifier(currentIdentifier);

      /*when number or braces follow identifier without space: reset currentPos*/
      /*to the position of the previous char*/
      if(isdigit(currentChar)){
         *currentPosition = *currentPosition - 1;
      }
      else if(currentChar == ']'){
         *currentPosition = *currentPosition - 1;
      }
      else if(currentChar == '['){
         *currentPosition = *currentPosition - 1;
      }

   }
   else if(currentChar=='\0'){

      symbolCode = eot;
   }
   /*neither terminal symbol nor end of text found on current position --> illegal symbol*/
   else{
      symbolCode = error;
   }

   free(currentIdentifier);
   free(currentNumber);
   return symbolCode;

}

现在是“边缘”识别程序中的致命召唤。首先,结构的标题

#ifndef GML_EDGE_STRUCT_H_INCLUDED
#define GML_EDGE_STRUCT_H_INCLUDED


typedef struct EdgeStruct* EdgeObj;

typedef struct EdgeStruct {

   int source;
   int target;
   int weight;

} EdgeStruct;

typedef EdgeObj EdgeDescription;

EdgeDescription createNewEdge(int src, int tgt, int wgt);
void destroyEdge(EdgeObj);

#endif // GML_EDGE_STRUCT_H_INCLUDED

实施

#include "GML_EDGE_STRUCT.h"
#include <stdio.h>
#include <stdlib.h>
EdgeDescription createNewEdge(int source, int target, int weight){

   EdgeDescription e;
   int bytesRequested = sizeof(EdgeStruct);

   e = malloc(bytesRequested);
   e->source = source;
   e->target = target;
   e->weight = weight;
   return e;
}

我知道,这几乎是代码;) 只是为了表明,我可以释放所有可以释放的东西。

我在过去两天搜索了我的问题,当然也是堆栈溢出,有数百个网站,有关malloc返回null的帖子等等。他们都说基本相同:没有足够的内存(也就是说,让它不太可能),或碎片堆,所以没有足够大小的mem块可用。

但是:我要求的是12个(字数:12个)字节来存储三个int属性。这似乎太多了。

我是否超出了一些我不知道的内部限制?

非常感谢帮助。

提前致谢 罗兰

编辑2012-11-24:

感谢您的回答。 但。问题必须具有更基本的性质。

因为:当我测试我的程序的其他部分(文件I / O)等,这些部分远不如解析器复杂,只从main()调用一次,我也不能malloc。我读取的文件大约有140个字节。即使我测试了与所有其他部分隔离的I / O部分,即使我将它们外包给不同的项目,我也没有从系统中获取内存。绝不是。我重新启动了电脑,一切。绝对。没有。变化

任何想法? 与此同时,我在这个项目中投入了太多时间,其中大部分是追踪那些记忆错误......: - ((

2 个答案:

答案 0 :(得分:3)

如果您怀疑使用了太多内存或将所有可用内存分段,那么您可以在运行时检查应用程序的内存使用情况。如果它占用了所有系统内存,则malloc因此而返回NULL。

如果以上情况不是您的情况,那么我会检查您的应用程序是否存在堆损坏。通常,当您覆盖堆结构时,会发生非常糟糕的事情。在调试模式下,编译器会为堆损坏检测添加一些额外的检查和红色区域。在发布模式下,破解堆结构通常会导致访问冲突。我可以想象,在极少数情况下,堆结构可能会被损坏,损坏可能会被解释为空间不足,因此malloc会返回NULL。

我会采用内存调试器的方式。 Valgrind多次救了我,但它可能在你的环境中无法使用。关于内存调试器的stackoverflow有很多主题。

答案 1 :(得分:1)

我不能说太多,只是一个观察。在GetNextSymbol()中,我看到读取的位数没有限制,因此存在缓冲区溢出的可能性。阅读标识符也是如此。

Graph()中的另一个,失败的Edge(sourceString, currentPosition)调用是在while循环中,结果永远不会被释放,AFAICS。