Entrance Exams
Govt. Exams
Dynamic array allocation requires pointer and malloc() with proper size calculation. VLAs are not standard C.
realloc() resizes a previously allocated memory block. It can increase or decrease the size and preserves existing data.
Accessing freed memory results in undefined behavior and is a critical bug. The memory may be reallocated for other purposes.
A memory leak occurs when allocated memory is not freed, consuming system resources without releasing them back.
free() is the standard function to deallocate memory previously allocated by malloc(), calloc(), or realloc().
int *ptr = malloc(sizeof(int));
if(ptr == NULL) printf("Failed");
else printf("Success");
In typical scenarios, malloc() successfully allocates memory and returns non-NULL pointer, printing 'Success'. NULL check is good practice for error handling.
calloc() takes two arguments (number of elements and size) and initializes all allocated bytes to zero, unlike malloc().
The <stdlib.h> header file contains declarations for malloc(), calloc(), realloc(), and free() functions.
malloc() returns a void pointer (void*) that can be cast to any pointer type.
malloc() is the standard C function for dynamic memory allocation. It returns a void pointer to the allocated memory.