ive been hearing this word but what is malloc?

Dani AI

Generated

A concise, practical explanation to follow the thread: asked what malloc is; pointed to searching and gave a good high-level intro. The key facts in one place and a few safe usage patterns.

malloc (prototype: void *malloc(size_t size); from <stdlib.h>) obtains a contiguous block of size bytes from the heap and returns a pointer to its start, or NULL on failure. In C the returned void * normally does not need a cast. calloc(count, size) allocates and zeroes memory; realloc(ptr, new_size) changes an existing block’s size and may move it. Always check returns before using the memory.

Simple patterns:

#include <stdlib.h>

size_t n = 100;
int *arr = malloc(n * sizeof *arr);
if (!arr) {
    /* handle allocation failure */
}
/* use arr */
free(arr);

For resizing safely:

int *tmp = realloc(arr, new_n * sizeof *arr);
if (tmp) arr = tmp; /* success */
else { /* realloc failed; arr still valid */ }

Common pitfalls and quick troubleshooting:

  • Forgetting free() causes leaks; freeing twice or using memory after free() causes crashes.
  • Don’t cast malloc’s result in C (it can hide missing stdlib.h warnings).
  • Use sizeof *ptr instead of hard-coded types to avoid errors.
  • Check for integer overflow when computing n * sizeof ....
  • Tools: run with Valgrind or compile with AddressSanitizer (-fsanitize=address -g) to find leaks and misuse.

This expands on ’s practical example with concrete usage, error handling patterns, and debugging tips to avoid the most common runtime problems.

Recommended Answers

All 3 Replies

Ever heard of google?...
Ever bothered to read threads on the same page with malloc in the title?

Ever been a Newbie yourself? :mrgreen:
Come on- try to be a little less abrupt next time. We'd like new members to feel welcomed here, not belittled.

ive been hearing this word but what is malloc?

Hi there:

malloc is for "memory allocation". While programming, we very often need to allocate free memory for variables of unknown length, which can not be decided at the time of programming. E.g. a program prompts people's names; since each person's name is different, the programmer is unlikely to allocate a fixed amount of memory to hold their names. (You may argue that it is possible to assign a whole bunch of memory; it is a bad practise and it is problem prone. )
A similar function is calloc().

A very good book to learn C language is C programming, A modern approach by K.N.King.

Does that answer your question?:cheesy:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.