C++中有关内存的思考

来源:互联网 发布:剪辑声音的软件 编辑:程序博客网 时间:2024/06/05 11:25
1
#include <iostream>
using namespace std;
void GetMemory(char *p)
{
p=(char *)malloc(100);
}
void Test(void)
{
char *str=NULL;
GetMemory(str);
strcpy(str,"Hello world");
printf(str);
}
int main()
{
Test();
    return 0;

}

运行Test函数后结果:程序崩溃。因为GetMemory并不能传递动态内存,Test函数中str一直是NULL。strcpy(str,"hello world")后系统崩溃

2
#include <iostream>
using namespace std;
char *GetMemory(void)
{
char p[]="hello world";
return p;
}
void Test(void)
{
char *str=NULL;
str=GetMemory();
printf(str);
}
int main()
{
Test();
    return 0;

}

运行Test函数后:乱码。因为GetMemory返回的是指向"栈内存”的指针,该指针不是NULL,但原先的内容已经被清除,新内容不可知

3
#include <iostream>
using namespace std;
void GetMemory(char **p,int num)
{
*p=(char *)malloc(num);


}
void Test(void)
{
char *str=NULL;
GetMemory(&str,100);
strcpy(str,"hello");
printf(str);
}
int main()
{
Test();
    return 0;

}

运行Test后:能够输出hello ,内存泄漏(不知道这个名词的百度一下可能会更明白)。

4
#include <iostream>
using namespace std;

void Test(void)
{
char *str=(char *)malloc(100);
strcpy(str,"hello");
free(str);
if(str!=NULL)
{
strcpy(str,"world");
      printf(str);
}
}
int main()
{
Test();
    return 0;

}

运行Test后:篡改了动态内存区的内容,后果难以预料,非常危险。因为free(str)后,str变为野指针,if(str!=NULL)语句不起作用。(不明白的可以百度一下 什么是野指针,这里不做过多的解释)

以上的4个程序均在VC++6.0上调试通过。

原创粉丝点击