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

王朝other·作者佚名  2006-01-09
宽屏版  字体: |||超大  

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

#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;

}

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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有