问:《C语言》指针那章的一道习题:编写一个函数alloc(n),用来在内存区新开辟一个连续的空间(n个字节)。再写一个函数free(p),将地址p

gwolf 2003-09-17 04:39:57
《C语言》指针那章的一道习题:编写一个函数alloc(n),用来在内存区新开辟一个连续的空间(n个字节)。再写一个函数free(p),将地址p开始的各单元释放。
能给点思路或代码均可。原题也有提示,可我不会做。在此请教各位。
...全文
577 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
gwolf 2003-09-20
  • 打赏
  • 举报
回复
Caoyu015(酷鱼一代) :
可否稍做解释?
Caoyu015 2003-09-19
  • 打赏
  • 举报
回复
//简单的实现.

#include <stdio.h>

const int MaxSize = 100 // MaxSize > n

char buffer[ n ];
#define Free( ptr ) Cfree( &ptr )

char * Alloc( int n )
{
*( int * )&buffer[ 0 ] = n;
return &buffer[ 2 ];
}

void CFree( void **ptr )
{
if( *ptr == &buffer[ 2 ] )
{
*( int * )&buffer[ 0 ] = 0;
*ptr = 0;
}
};

playboyxp 2003-09-19
  • 打赏
  • 举报
回复
#include <stdio.h>
int *alloc(int n)
{
int *p;
p=malloc(sizeof(int)*n);
return p;
}
main()
{
int n,*p;
scanf("%d",&n);
p=alloc(n);
free(p);
}
lyff8neo 2003-09-17
  • 打赏
  • 举报
回复
mark
Andy84920 2003-09-17
  • 打赏
  • 举报
回复
楼主的意思是自己去实现MALLOC和FREE,不是去用标准函数库!
去看看STDLIB头文件.自己实现我还不知道怎么想.
老鱼趣多多 2003-09-17
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

int main()
{
char *str=NULL;
int n;
printf("Enter the size you want malloc!\n");
scanf("%d",&n);
str=(char *)malloc(sizeof(char)*n);
if(str==NULL)//内存分配不成功
{
printf("malloc failed!\n");
exit(0);
}

memset(str,0,n);//内存中的垃圾内容清空
free(str);
printf("the memeory is be freed!\n");
return 0;
}
psprite 2003-09-17
  • 打赏
  • 举报
回复
#include <stdlib.h> /* For _MAX_PATH definition */
#include <stdio.h>
#include <malloc.h>

void main( void )
{
char *string;

/* Allocate space for a path name */
string = malloc( _MAX_PATH );
if( string == NULL )
printf( "Insufficient memory available\n" );
else
{
printf( "Memory space allocated for path name\n" );
free( string );
printf( "Memory freed\n" );
}
}
ern 2003-09-17
  • 打赏
  • 举报
回复
去看看malloc的源代码?呵呵

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧