一个关于malloc的面试题

前两天看了一个关于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的正确写法应该是: code

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);
}
相关文章
相关标签/搜索