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.
| Category | stdlib.h utilities |
|---|---|
| Kind | Library function |
| Header | <stdlib.h> |
| C standard | C89 / C90 |
📝 Syntax
void *malloc(size_t size);
⚙️ Parameters
| size Required | The 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 stdlib.h functions
📚 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.