Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Heap and Stack in C Programming

Tech May 1 59

What is Heap?

Heap refers to a region of memory used for dynamic allocation during program execution. It is typically larger than stack memory and is allocated when the program starts.

Usage of Heap

  1. The heap is primarily used for storing complex data structures such as dynamically allocated arrays or structs.
  2. Memory allocated on the heap must be manually freed to prevent memory leaks.

Example code:

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

int main() {
    int *array = (int *)malloc(5 * sizeof(int));
    if (array == NULL) {
        perror("Failed to allocate memory");
        return 1;
    }
    
    array[0] = 10;
    array[1] = 20;
    
    printf("Value at index 0: %d\n", array[0]);
    
    free(array);
    
    printf("Value at index 1 after freeing: %d\n", array[1]);
    return 0;
}

Output:

Value at index 0: 10
Value at index 1 after freeing: 0

What is Stack?

Stack is a memory area used for storing function calls and local variables. Its size is usually fixed and limited, and it keeps track of the execution state of a program.

Stack in Function Calls

  1. The stack holds context information for function calls, including parameters, local variables, and return addresses.
  2. Data stored on the stack has a short lifetime and is automatically deallocated upon function completion.

Example code:

#include <stdio.h>

void exampleFunction() {
    int localValue = 5;
    printf("Local value: %d\n", localValue);
}

int main() {
    exampleFunction();
    return 0;
}

Output:

Local value: 5

Stack in Multithreading

  1. Multiple threads can be created where each runs its own stack.
  2. Each thread’s stack is independent and allows concurrent execution.

Example code:

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

#define THREAD_COUNT 3

void* workerThread(void* arg) {
    int id = *(int*)arg;
    printf("Thread %d is executing\n", id);
    return NULL;
}

int main() {
    pthread_t threads[THREAD_COUNT];
    int ids[THREAD_COUNT];
    
    for (int i = 0; i < THREAD_COUNT; i++) {
        ids[i] = i;
        pthread_create(&threads[i], NULL, workerThread, &ids[i]);
    }
    
    for (int i = 0; i < THREAD_COUNT; i++) {
        pthread_join(threads[i], NULL);
    }
    
    printf("All threads completed\n");
    return 0;
}

Output:

Thread 0 is executing
Thread 1 is executing
Thread 2 is executing
All threads completed

Summary

  1. Heap and stack are distinct memory regions in C with different purposes and management styles.
  2. Heap supports dynamic allocation and requires manual memory handling.
  3. Stack handles function calls and local variables with automatic allocation and deallocation.
  4. Choosing between heap and stack depends on the scope and lifecycle of data.
  5. Proper memory management is essential to avoid issues like memory leaks and dangling pointers.

Related Articles

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Comprehensive Guide to Hive SQL Syntax and Operations

This article provides a detailed walkthrough of Hive SQL, categorizing its features and syntax for practical use. Hive SQL is segmented into the following categories: DDL Statements: Operations on...

Understanding the MP4 File Format and Analysis

Table of Contents Overview Fundamentals of the MP4 Format Key Concepts of the Container Format Box Structure Track Samples Sample Tables Chunks Detailed Explanation of Core Boxes Additional Boxes...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.