问题4:
void GetMemory( char *p )
{
p = (char *) malloc( 100 );
}
void Test( void )
{
char *str = NULL;
GetMemory( str );
strcpy( str, "hello world" );
printf( str );
}
解析:GetMemory( str )进行的是指针的输入申请内存,在传入参数并不能改变传入形参的值,所以
char *str = NULL;
GetMemory( str ); 后str的值也是NULL(如果想要改变其形式参数的值,在参数传入过程中需要传入是形参是函数值的传入char &p)
问题5:
char *GetMemory( void )
{
char p[] = "hello world";
return p;
}
void Test( void )
{
char *str = NULL;
str = GetMemory();
printf( str );
}
解析:返回的数值是null,因为p是局部变量,只存在GetMemory中当超过这个返回p被释放,所以str = GetMemory();的赋值是不存在的
问题6:
void GetMemory( char **p, int num )
{
*p = (char *) malloc( num );
}
void Test( void )
{
char *str = NULL;
GetMemory( &str, 100 );
strcpy( str, "hello" );
printf( str );
}
解析:代码可以正常的运行,但是还有些问题
(1)在内存申请过程中没有判断内存申请是否成功过
(2)对于申请的堆内存没有进行释放
(3)在printf输出字符串时应该改为printf("%s", str);否则可以使用字符串攻击
拓展printf的输出顺序:
printf的输出顺序是从右到左一次输出的例如:printf("%d,%d\n", a, b);输出是先输出b,然后在输出a的
(如有疑问可以查找网址:http://bbs.csdn.net/topics/340075180)