前两天看了一个关于malloc的面试题,题目是这样的:
void GetMemory(char *p , int nlen)
{
p = (char*)malloc(nlen);
}
void main()
{
char* str=NULL;
GetMemory(str , 11);
strcpy(str, "hello world");
printf(str);
}
对于这个问题,我第一眼看到的是,字符串长度的问题和malloc出来的内存块没有free的问题。字符串”hello world”在结尾包含一个’\0’ ,所以长度为12,而malloc出来的内存块必须要free掉,不然就会出现野指针。这两两个问题比较好看出来。
但是这都不是问题的关键,问题的关键在于函数的传值,我们要改变实参的值,传入的必须是引用类型和指针类型。
str也确实是一个指针,但是当我们需要改变这个指针的值的时候,我们必须传入str的地址即&str;所以GetMemory的正确写法应该是:
void GetMemory(char **p , int nlen)
{
*p = (char*)malloc(nlen);
}
完整程序:
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
void GetMemory(char **p , int nlen)
{
*p = (char*)malloc(nlen);
}
Void main()
{
char* str = NULL;
GetMemory(&str , 128);
strcpy(str , "hello world");
printf(str);
free(str);
}