0% found this document useful (0 votes)
16 views6 pages

Dynamic Memory Allocation Pointers

The document explains pointers as variables that store memory addresses and highlights their importance in efficient memory management and data structures. It differentiates between static and dynamic memory allocation, detailing functions like malloc, calloc, realloc, and free for managing dynamic memory in C. The conclusion emphasizes the necessity of proper memory management to prevent memory leaks.

Uploaded by

bharti saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views6 pages

Dynamic Memory Allocation Pointers

The document explains pointers as variables that store memory addresses and highlights their importance in efficient memory management and data structures. It differentiates between static and dynamic memory allocation, detailing functions like malloc, calloc, realloc, and free for managing dynamic memory in C. The conclusion emphasizes the necessity of proper memory management to prevent memory leaks.

Uploaded by

bharti saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Dynamic Memory Allocation & Pointers

Understanding pointers and memory allocation in C


Introduction to Pointers

A pointer is a variable that stores the memory address of another variable.

Why use pointers?

- Efficient memory management

- Direct access to memory

- Used in data structures like linked lists


Memory Allocation Types

1. Static Allocation:

- Memory is allocated at compile time

- Fixed size, cannot be changed during execution

2. Dynamic Allocation:

- Memory is allocated at runtime

- Flexible, can allocate and deallocate memory as needed


Dynamic Memory Allocation

Functions used for dynamic memory allocation in C:

- malloc(size): Allocates memory of given size

- calloc(n, size): Allocates memory for an array of n elements

- realloc(ptr, new_size): Resizes previously allocated memory

- free(ptr): Deallocates memory to avoid memory leaks


Example Code

Example: Allocating memory using malloc

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr;

ptr = (int*) malloc(5 * sizeof(int));

if (ptr == NULL) {

printf("Memory not allocated.\n");

return 1;

printf("Memory allocated successfully.\n");

free(ptr);

return 0;

}
Conclusion

- Pointers store addresses and help in efficient memory management.

- Dynamic memory allocation allows flexible use of memory.

- Functions like malloc, calloc, realloc, and free help manage memory.

- Proper memory management is crucial to avoid memory leaks.

You might also like