C Malloc Pitfalls

The cluster focuses on common issues with malloc in C programming, including failure to check NULL returns, memory overcommit on Linux, uninitialized memory risks, and alternatives like Guard Malloc or calloc.

➡️ Stable 0.5x Programming Languages
3,694
Comments
20
Years Active
5
Top Authors
#1662
Topic ID

Activity Over Time

2007
1
2008
21
2009
53
2010
54
2011
104
2012
108
2013
126
2014
245
2015
181
2016
362
2017
176
2018
195
2019
249
2020
220
2021
276
2022
389
2023
306
2024
260
2025
329
2026
39

Keywords

RAM e.g IMHO NULL nixdoc.net VLA DNS XML malloc.conf SMP malloc memory free glibc linux allocations code kernel library allocation

Sample Comments

tonyedgecombe Aug 31, 2018 View on HN

I suspect it's the same with memory, nobody checks that malloc doesn't return 0.

jesprenj Apr 9, 2022 View on HN

If malloc() damages the running system, why even implement it in the standard library?

xsmasher Jul 15, 2010 View on HN

Good tip; I believe Guard Malloc does this for you.

ygra Aug 29, 2017 View on HN

Wasn't in the case on Linux due to overcommit that allocations always succeed anyway? So a novice C developer, working on 64-bit Linux may assume that malloc calls never have to be checked.

Plenty of code runs on systems without that behavior. Graceful handling of malloc failure is still useful.

nurpax Jun 15, 2024 View on HN

The same can happen with C malloc/free too.

cozzyd Feb 22, 2020 View on HN

If you don't free, malloc doesn't need all that overhead

aetherspawn Nov 6, 2021 View on HN

You can probably mitigate this with malloc_s or similar that writes 0 bytes to the entire allocated space before returning.

weinzierl Feb 27, 2025 View on HN

It's not even guaranteed that it doesn't allocate, so a malloc(0) could cause an out of memory.

TylerE May 16, 2023 View on HN

Who needs memory safety? Just correctly use malloc and free on every possible code path. Easy and simple!