首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

free()的有关问题

2012-02-22 
free()的问题。#includestdlib.h#includestdio.h#includestring.h#includeiostream.hchar*GetMemor

free()的问题。
#include   <stdlib.h>
#include   <stdio.h>
#include   <string.h>
#include   <iostream.h>

char   *GetMemory()
{
char   *p   =   (char   *)   malloc(11);
p   =   "hello   world ";
return   p;
}

void   Test()
{
char   *str   =   NULL;
str   =   GetMemory();
if(str!=NULL)
{
printf(str);
cout < <endl;
free(str);
}
}

void   main()
{
Test();
}

运行到free(str);时出错,不知道什么原因?

[解决办法]
char *GetMemory()
{
char *p = (char *) malloc(11);
printf( "orign: %d ", p);
p = "hello world ";
printf( "then: %d ", p);
return p;
}

这样就明白了
[解决办法]
char *GetMemory()
{
char *p = (char *) malloc(11);
p = "hello world ";/*这里让p重新指向了内存中的一个常量字符串,原先保存的首地址丢了*/
return p;
}
----------------------
内存泄露了。。。


char *GetMemory()
{
char *p = (char *) malloc(11);
strcpy(p, "hello world ");
return p;
}

[解决办法]
"hello world "这个还包括了一个 '\0 '!!!
你p的空间分配小了个.

char *p = (char *) malloc(12);这样应该就没事的.

热点排行