先来上一个到处可见的错误程序实例:

#include <iostream>
using namespace std;

void GetMemory( char *p )
{
	p = (char *)malloc(100);
}

int main()
{
	char *str = NULL;
	GetMemory(str);
	strcpy(str, "hello world" );

	return 0;
}
         我们来看一下错在哪里? 在main中调用GetMemory函数, str做的是入参, 这就有问题了, 既然是入参, 那又怎能指望GetMemory去改变它的值呢? 先把空指针传给p, 又对p进行赋值, 这是为哪般?

         执行GetMemory后, str依然是空指针, 拷贝的时候, 自然崩溃。 修改方法是: 让str做出参(利用引用或者二维指针), 比较easy, 我就不多说了。


本文转载:CSDN博客