您的位置:首页 > 移动开发 > IOS开发

究竟需要给Malloc函数分配多少内存才算合适呢?

2005-06-21 20:09 501 查看
下面是一个用指针操作链表的程序,网上的例子.觉得不错.很典型.先拿它来开刀.
#include <iostream>
#include "stdafx.h"
using namespace std;
struct listNode
{
 long data;
 struct listNode *nextPtr;
};
typedef struct listNode LISTNODE;
typedef LISTNODE * LISTNODEPTR;
LISTNODEPTR list(LISTNODEPTR , int); // 此处不同
void printlist(LISTNODEPTR);
void freelist(LISTNODEPTR); // 增加
void _tmain(int argc, _TCHAR* argv[])
{
 LISTNODEPTR newPtr=NULL;
 int i,a;
 for(i=0;i<3;i++){
  printf("please enter a number/n");
  scanf("%d,",&a);
  newPtr = list(newPtr,a); // 此处注意
 }
 printlist(newPtr);
 freelist(newPtr); // 此处
 return 0;
}
LISTNODEPTR list(LISTNODEPTR sPtr, int a)
{
 if ( sPtr != NULL )
  sPtr->nextPtr = list( sPtr->nextPtr, a ); // 递归,向后面的节点上加数据。
 else
 {
  sPtr =(LISTNODEPTR) malloc(sizeof(LISTNODE)); // 注意,是节点的尺寸,类型转换,关于这里,发现了点问题. 
  sPtr->nextPtr = NULL;
  sPtr->data = a;
 }
 return sPtr;
}
void freelist(LISTNODEPTR sPtr )
{
 if ( sPtr != NULL )
 {
  freelist( sPtr->nextPtr ); // 递归, 先释放后面的节点
  free( sPtr ); // 再释放本节点
 }
 else //
  return ; // 此两行可不要
}
void printlist(LISTNODEPTR currentPtr)
{
 if(currentPtr==NULL)
  printf("The list is empty/n");
 else
 {
  printf("This list is :/n");
  while(currentPtr!=NULL)
  {
   printf("%d-->",cu
4000
rrentPtr->data);
   currentPtr=currentPtr->nextPtr; // 这里不一样
  }
  printf("NULL/n/n");
 }
}

在那里,代码简化为:
LISTNODEPTR sPtr;
sPtr =(LISTNODEPTR) malloc(sizeof(LISTNODE));
sPtr明明是一个指向listNode结构的指针,为什么不分配给它一个指针大小的内存呢?像这样:
sPtr=(LISTNODEPTR)malloc(sizeof(LISTNODEPTR));     //同时,把释放内存函数改成如下:
void freelist(LISTNODEPTR sPtr )
{
 if ( sPtr != NULL )
 {
    freelist( sPtr->nextPtr );             // 递归, 先释放后面的节点
  }
 else
   free( sPtr );                                   // 再释放本节点 
   return; 
 } 

如果不改释放内存函数,程序在释放内存时出错.什么原因呢?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  null list struct iostream
相关文章推荐