Course Content
C Tutorial
About Lesson

Memory Manipulation (stdlib.h)

Memory manipulation is a fundamental aspect of programming, particularly in C, where direct memory access provides a powerful toolset for developers. The stdlib.h library in C offers various functions that enable memory manipulation, allowing programmers to efficiently allocate, deallocate, and modify memory.

Dynamic Memory Allocation

One of the primary functions in stdlib.h for memory manipulation is malloc(). This function dynamically allocates memory during the execution of a program. Developers can request a specific amount of memory, and malloc() returns a pointer to the allocated memory block. For instance:

#include <stdlib.h>

int *ptr;
ptr = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5 integers

Remember, after dynamic allocation, it’s crucial to release this memory when it’s no longer needed to avoid memory leaks. This is where the free() function comes into play:

Memory Deallocation

The free() function in stdlib.h is used to deallocate memory that was previously allocated using malloc(). It’s essential to free dynamically allocated memory to prevent memory leaks, which occur when memory is not deallocated properly. Here’s an example:

int *ptr;
ptr = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5 integers
// Use ptr...
free(ptr); // Deallocate memory when done

Memory Copy and Manipulation

C provides efficient ways to copy and manipulate memory blocks using functions like memcpy() and memset() available in stdlib.h.

  • memcpy(): This function is used to copy a specified number of bytes from one memory location to another. It takes the destination, source, and number of bytes to copy as arguments.
#include <string.h>

char source[] = "Hello, World!";
char destination[20];

memcpy(destination, source, strlen(source) + 1); // Copy source to destination

  • memset(): This function allows setting a block of memory to a specified value. It takes the memory address, value to set, and the number of bytes to set as arguments.
#include <string.h>

char str[50];

memset(str, 'A', 50); // Set the first 50 bytes of str to 'A'