- #include <stdio.h>
- #include <malloc.h>
- #include <string.h>
- #include <iostream.h>
- /*
- * Test.cpp
- *
- * Created on: Oct 22, 2008
- * Author: root
- */
- char *GetMemory(void) {
- char p[] = "hello world";
- return p;
- }
- void Test(void) {
- char *str = NULL;
- str = GetMemory();
- printf(str);
- }
- void GetMemory2(char *p) {
- p = (char *) malloc(100);
- }
- void Test2(void) {
- char *str = NULL;
- GetMemory2(str);
- strcpy(str, "hello world");
- printf(str);
- }
- void Test3(void) {
- char *str = (char *) malloc(100);
- strcpy(str, "hello");
- free(str);
- if(str != NULL){
- strcpy(str, "world");
- printf(str);
- }
- }
- void GetMemory4(char **p, int num) {
- *p = (char *) malloc(num);
- }
- void Test4(void) {
- char *str = NULL;
- GetMemory4(&str, 100);
- strcpy(str, "hello");
- printf(str);
- }
- void testSizeOf(){
- cout << endl << " sizeof(char) "<< sizeof(char) << endl;
- cout << " ssizeof(int) "<< sizeof(int) << endl;
- cout << " sizeof(unsigned int) "<< sizeof(unsigned int) << endl;
- cout << " sizeof(long) "<< sizeof(long) << endl;
- cout << " sizeof(unsigned long) "<< sizeof(unsigned long) << endl;
- cout << " sizeof(float) "<< sizeof(float) << endl;
- cout << " sizeof(double) "<< sizeof(double) << endl;
- cout << " sizeof(void *) "<< sizeof(void *) << endl;
- }
- int main() {
- //Test();
- //Test2();
- //Test3();
- Test4();
- testSizeOf();
- return 0;
- }
Test()的运行结果是未知,因为GetMemory返回的是指向“栈内存”的指针,该指针的地址不是 NULL,但其原现的内容已经在函数退出后被清除,新内容不可知。
Test2()的运行结果是程序崩溃。因为GetMemory2并不能传递动态内存(编译器总是要为函数的每个参数制作临时副本,指针参数p的副本是 _p,编译器使 _p = p。传入的是一个指针,在本例中,_p申请了新的内存,只是把_p所指的内存地址改变了,但是p丝毫未变),Test函数中的 str一直都是 NULL。strcpy(str, "hello world");将使程序崩溃。
Test4()的运行结果是hello。因为传入的是指针的指针,所以_p的改变,也就是改变传入的参数,故str被正确的复制。
Test3()的运行结果是输出world。篡改动态内存区的内容,后果难以预料,非常危险。因为free(str);之后,str成为野指针,但是str并没有置成空,所以if(str != NULL)语句不起作用。