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

下面是一个用指针操作链表的程序,网上的例子.觉得不错.很典型.先拿它来开刀.

#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-->",currentPtr->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; 
 }
 

如果不改释放内存函数,程序在释放内存时出错.什么原因呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值