When and why to use malloc?

malloc is used for dynamic memory allocation. As said, it is dynamic allocation which means you allocate the memory at run time. For example when you don’t know the amount of memory during compile time. One example should clear this. Say you know there will be maximum 20 students. So you can create an array … Read more

What is the difference between Static and Dynamic arrays in C++?

Static arrays are created on the stack, and have automatic storage duration: you don’t need to manually manage memory, but they get destroyed when the function they’re in ends. They necessarily have a fixed size at compile time: int foo[10]; Arrays created with operator new[] have dynamic storage duration and are stored on the heap … Read more

Proper usage of realloc()

Just don’t call free() on your original ptr in the happy path. Essentially realloc() has done that for you. ptr = malloc(sizeof(int)); ptr1 = realloc(ptr, count * sizeof(int)); if (ptr1 == NULL) // reallocated pointer ptr1 { printf(“\nExiting!!”); free(ptr); exit(0); } else { ptr = ptr1; // the reallocation succeeded, we can overwrite our original … Read more

Difference between static memory allocation and dynamic memory allocation

This is a standard interview question: Dynamic memory allocation Is memory allocated at runtime using calloc(), malloc() and friends. It is sometimes also referred to as ‘heap’ memory, although it has nothing to do with the heap data-structure ref. int * a = malloc(sizeof(int)); Heap memory is persistent until free() is called. In other words, … Read more

Dynamic memory access only works inside function

The reason for this bug is that the data used by the create_array function is a local variable that only exists inside that function. The assigned memory address obtained from malloc is only stored in this local variable and never returned to the caller. Consider this simple example: void func (int x) { x = … Read more