工程師應知道的0x10個問題(14): 動態記憶體配置

MuLong PuYang
5 min readMar 19, 2022

--

英文參考網址

A ‘C’ Test: The 0x10 Best Questions for Would-be Embedded Programmers

中文參考網址

C語言測試 應知道的0x10個基本問題

原文翻譯

14. Although not as common as in non-embedded computers, embedded systems still do dynamically allocate memory from the heap. What are the problems with dynamic memory allocation in embedded systems?

雖然在非嵌入式系統上並不常見,嵌入式系統仍然在heap上做動態的配置記憶體。做動態記憶體配置在嵌入式系統上會有什麼問題?

Here, I expect the user to mention memory fragmentation, problems with garbage collection, variable execution time, etc. This topic has been covered extensively in ESP, mainly by Plauger. His explanations are far more insightful than anything I could offer here, so go and read those back issues! Having lulled the candidate into a sense of false security, I then offer up this tidbit:

這裡,我預期使用者描述到記憶體碎片,垃圾回收的問題,變數的執行時間等。這些議題已經被Plauger在ESP雜誌上廣泛的涉及。他的解釋遠是更深刻見解的遠超任何我在這裡可以提供的,所以去並且讀這些議題。緩和應試者進入一個虛假安全的感覺後,接著我會提供這個小題目

注:原文這邊:"I then offer up this tidbit",因為tidbit有美味小吃或者是小片珍饈的意思,所以這邊我使用中文來源的譯法將tidbit翻成小題目

What does the following code fragment output and why?

以下的程式片段輸出是什麼並且為什麼這樣輸出?

char *ptr;

if ((ptr = (char *)malloc(0)) == NULL) {

puts(“Got a null pointer”);

}

else {

puts(“Got a valid pointer”);

}

This is a fun question. I stumbled across this only recently, when a colleague of mine inadvertently passed a value of 0 to malloc, and got back a valid pointer! After doing some digging, I discovered that the result of malloc(0) is implementation defined, so that the correct answer is ‘it depends’. I use this to start a discussion on what the interviewee thinks is the correct thing for malloc to do. Getting the right answer here is nowhere near as important as the way you approach the problem and the rationale for your decision.

這是個有趣的問題。我在最近偶然發現,當一個我的同事不慎的傳入0的數值進入malloc,然後得到一個有效的指標!在做了一些挖掘之後,我發現這個malloc(0)的結果是實作定義的,所以正確的答案是"要看情況"。我使用這個來開啟一個討論來看應試者怎麼思考malloc所做的正確的事情。這裡得到正確的答案並不比你靠近這個問題以及你決定的原理闡述重要。

注1:I discovered that the result of malloc(0) is implementation defined, so that the correct answer is ‘it depends’.
這裡implementation defined我覺得應該要譯成實作定義的,如果有讀者覺得有更好的譯法歡迎留言告訴我。另外後面的‘it depends’,我查了一下It depends這篇的解說,基本上是要看情況的意思,這裡其實我真的很不懂作者想表達的意思,如果有讀者理解這個作者想表達的意思,歡迎留言告訴我

自我實作以及理解

注1: 以下是我的自我實作以及理解的部分,不保證正確而且很有可能描述不清楚或者是有錯誤,讀者若發現有可以更正的地方也歡迎留言告訴我注2: 以下皆簡單的使用Ubuntu 20.04虛擬機做測試,並非真實的嵌入式系統,所以Ubuntu 20.04出來的成果可能會與嵌入式系統上的有差異注2: 以下皆簡單的使用Ubuntu 20.04虛擬機做測試,並非真實的嵌入式系統,所以Ubuntu 20.04出來的成果可能會與嵌入式系統上的有差異

我們照著原文刻出以下的程式碼

輸出結果為確實可以拿到有效的指標

Got a valid pointer

網路上搜尋malloc(0)可以得到不同的討論文章,由於我對這方面真的不了解所以我大約找了三個連結,有興趣的讀者也可以搜尋看看各種不同的答案

以下兩個是用VC的,不是GCC,不過或許兩者的編譯器在處理這個問題上可能有相近之處
1) C語言中關於malloc(0)問題
2) ptr = (char *)malloc(0)
這一篇stack overflow就是純討論,似乎沒有限定在哪一個編譯器
3) What's the point of malloc(0)?

--

--