malloc() Allocate an uninitialized memory block

malloc() Allocate an uninitialized memory block

malloc() allocates uninitialized storage and returns a pointer, or NULL on failure. Check size multiplication for overflow and free the pointer after use.

Categorystdlib.h utilities
KindLibrary function
Header<stdlib.h>
C standardC89 / C90

📝 Syntax

void *malloc(size_t size);

⚙️ Parameters

size RequiredThe number of bytes to allocate.

Returns: Returns a pointer to the allocated storage on success, or NULL if allocation fails. The allocated contents are uninitialized.

▶ Example

Edit the C code below and click Run; the server compiles and executes it:

Output:

10 20 30 40 50
⚠️ Warning Check for NULL before use and call free() when finished. Do not read uninitialized objects or access beyond the allocated region.
💡 Tip Use count * sizeof *ptr to avoid repeating the type. Avoid relying on zero-size allocation behavior, which is implementation-defined.

📚 Related Tutorials

❓ FAQ

QIs memory returned by malloc initialized to zero?
ANo. Its initial contents are indeterminate. Use calloc() for zero-initialized bytes or initialize the storage yourself after malloc().
QDo I need to cast the return value of malloc in C?
ANo. A void * converts implicitly to another object pointer type. Include <stdlib.h> and assign it directly; a cast can also hide a missing declaration.
QHow can I avoid size-calculation overflow when allocating an array with malloc?
ABefore multiplying, ensure the element count does not exceed the maximum size_t value divided by the element size, then compute count * sizeof *ptr. The multiplication occurs before malloc is called; if it overflows, malloc receives a smaller byte count and cannot know the actual requirement. Check for NULL after allocation as well.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏