此版本的C程序内存不足。有人请告诉我为什么它的内存不足

时间:2014-03-21 18:07:27

标签: c

此版本的C程序内存不足。有人请告诉我为什么它的内存不足。我在采访中遇到了这个问题。

typedef struct pnode
               {
                 void * ptrData;
                 struct pnode *pNext;
               } NODE ;

void AddNode(NODE *ptrParent, int z);
void Cleanup(NODE *pStart);
void freeList(NODE *pHead);

int main(int argc, char *argv[])
{
     NODE *pCurrent;
     NODE start;
     int x =22;
     while (1)
      {
          start.pNext=(NODE *)NULL;
          x=15;
          start.ptrData = (void *)&x;
          pCurrent=&start;
          for (x=0; x<2000; x++)
          {    AddNode(pCurrent,x);
                pCurrent=pCurrent->pNext;
          }
          Cleanup(&start);
      };
}

/*Add Node*/
void AddNode(NODE *ptrParent, int z)
{
      NODE *ptrNew;
      int *ptrData = (int *) NULL;

      /*Allocating memory to ptrNew*/
       ptrNew = (NODE *)malloc(sizeof(NODE));
       if ((NODE *) NULL == ptrNew)
       {
             printf("Out of memory! Exiting\n");
             exit (1);
        }
       /*Allocating memory to ptrData. Please let me know why am in getting out of memory error*/
       ptrData= (int *) malloc(sizeof(int));
       if ((int *) NULL == ptrData)
       {
             printf("Out of memory! Exiting\n");
             exit (1);
        }

        *ptrData = z;
        ptrNew->ptrData = (void *)ptrData;
        ptrNew->pNext=(NODE *) NULL;
        ptrParent->pNext = ptrNew;
}

void Cleanup(NODE *pStart)
{
    if ((NODE *)NULL != pStart->pNext)
    {
        freeList(pStart->pNext);
    }
    pStart->pNext=(NODE *)NULL;
    *((int *)pStart->ptrData) = 0;
}

void freeList(NODE *pHead)
{    NODE *pNext;
     pNext = pHead->pNext;
     if (NULL != pHead->pNext)
     {
          freeList(pNext);
          free(pNext);
     }
}

1 个答案:

答案 0 :(得分:0)

如果您在不破坏语法突出显示的情况下无法正确撰写问题,那么您可以更快地得到答案。问题是AddNode()

 ptrData= (int *) malloc(sizeof(int));
 if ((int *) NULL == ptrData)
 {
     printf("Out of memory! Exiting\n"); exit (1); }
 }

将在free()

中分配不是freeList()'d的内存

要修复,您需要将freeList()更改为:

 void freeList(NODE *pHead)
 {
     NODE *pNext;
     pNext = pHead->pNext;
     if (NULL != pHead->pNext)
         {
         freeList(pNext);
         free(pNext->ptrData);
         free(pNext);
         }
 }