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

Mon*_*rns 6 c memory heap malloc null

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

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

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

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

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

这次通话是两次.第一次,一切顺利.然后,由于根据gml语法可能出现1到n个边,因此代码进入while循环,其中为同一指针分配指向新Edge Struct的指针,只要在输入流中找到Edges即可.循环中第一次调用边缘识别例程,总共第二次调用(第一个在进入循环之前发生,参见ma),由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;
 }
Run Code Online (Sandbox Code Playgroud)

}

这里是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;

}
Run Code Online (Sandbox Code Playgroud)

现在是"边缘"识别程序中的致命召唤.首先,结构的头

#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
Run Code Online (Sandbox Code Playgroud)

实施

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

非常感谢帮助.

在此先感谢罗兰

编辑2012-11-24:

谢谢你的回答.但.问题必须是更基本的问题.

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

有任何想法吗?与此同时,我已经在这个项目中投入了太多时间,其中大部分都是跟踪那些内存错误......: - (((

Ola*_*che 1

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

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