读书人

free()的有关问题

发布时间: 2012-02-22 19:36:55 作者: rapoo

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);这样应该就没事的.

读书人网 >C++

热点推荐