一个关于malloc的面试题
生活随笔
收集整理的這篇文章主要介紹了
一个关于malloc的面试题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
前兩天看了一個關于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); }
轉載于:https://my.oschina.net/u/586637/blog/217710
總結
以上是生活随笔為你收集整理的一个关于malloc的面试题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Struct2小结:
- 下一篇: POJ 3617 Best Cow Li