Forum

Notifications
Clear all

Learn Malloc()

1 Posts
1 Users
0 Reactions
10 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

The malloc() function in C stands for memory allocation, and it’s used to dynamically allocate memory during a program’s runtime. It’s part of the <stdlib.h> library and is a cornerstone of dynamic memory management in C.


🧠 What malloc() Does

  • Allocates a block of memory on the heap, not the stack.
  • Returns a void* pointer to the beginning of the allocated memory.
  • The memory is uninitialized, meaning it contains garbage values.
  • If allocation fails, it returns NULL.

📦 Syntax

void* malloc(size_t size);
  • size: Number of bytes to allocate.
  • You typically cast the result to the desired pointer type.

🧪 Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = (int *)malloc(5 * sizeof(int));  // Allocate space for 5 integers

    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        arr[i] = i * i;
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    free(arr);  // Always free allocated memory
    return 0;
}

⚠️ Best Practices

  • Always check if malloc() returns NULL.
  • Use sizeof() to avoid hardcoding byte sizes.
  • Always free() memory after use to prevent memory leaks.

🛡️ Security Implications

  • Improper use of malloc() can lead to:
    • Buffer overflows
    • Use-after-free vulnerabilities
    • Memory leaks
  • These are common targets in cybersecurity exploits, especially in C/C++ applications.

For a deeper dive, check out GeeksforGeeks’ guide on dynamic memory allocation or FreeCodeCamp’s explanation of malloc in C.

 


   
Quote
Share: