ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Dynamic Memory Allocat…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    7 min read
    Topic 37 of 39
    Topic Study Note Illustration
    37

    Dynamic Memory Allocation: calloc and realloc, goto

    In C programming, dynamic memory allocation is used when you don’t know the amount of memory your program will need during its execution. This allows you to...

    Dynamic Memory Allocation: calloc and realloc, goto

    In C programming, dynamic memory allocation is used when you don’t know the amount of memory your program will need during its execution. This allows you to allocate memory at runtime, giving your programs more flexibility. The calloc() and realloc() functions are crucial for managing dynamic memory, while the goto statement offers an alternative flow control mechanism, although it's used less frequently due to concerns about readability and maintainability.


    1. Dynamic Memory Allocation: calloc() and realloc()

    Dynamic memory allocation in C is done using functions like malloc(), calloc(), realloc(), and free(), all of which are part of the C standard library defined in <stdlib.h>. Let's dive deeper into the two functions you're asking about: calloc() and realloc().

    calloc() Function

    The calloc() function allocates memory for an array of elements, initializing all of them to zero.

    Syntax:
    void* calloc(size_t num_elements, size_t element_size);
    
    • num_elements: Number of elements to allocate.
    • element_size: Size of each element in bytes.
    How It Works:
    • calloc() allocates memory for the specified number of elements of the specified size, and also initializes each byte to zero.
    • It's useful when you want an array of initialized memory, which is not guaranteed with malloc().
    Example:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int* arr;
        size_t n = 5;
    
        // Allocating memory for an array of 5 integers
        arr = (int*)calloc(n, sizeof(int));
    
        if (arr == NULL) {
            printf("Memory allocation failed.\n");
            return 1;  // Exit if memory allocation fails
        }
    
        // Print the initialized array (should print 0 for each element)
        for (size_t i = 0; i < n; i++) {
            printf("arr[%zu] = %d\n", i, arr[i]);
        }
    
        free(arr);  // Free allocated memory
        return 0;
    }
    

    Explanation:

    • In this example, calloc() allocates memory for an array of 5 integers (n = 5), each of size sizeof(int).
    • All elements are initialized to 0, and the program prints the value of each element (which will be 0).
    • After usage, free() is called to release the allocated memory.

    Why Use calloc()?

    • It initializes the allocated memory to zero. This is useful when working with arrays or structures where you want to avoid garbage values.
    • The main difference between malloc() and calloc() is that malloc() allocates memory but does not initialize it, whereas calloc() both allocates and initializes it to zero.

    realloc() Function

    The realloc() function changes the size of a previously allocated memory block. It’s useful when you need to resize an array or a dynamically allocated block of memory.

    Syntax:
    void* realloc(void* ptr, size_t new_size);
    
    • ptr: A pointer to the memory block you want to resize.
    • new_size: The new size (in bytes) to which the memory block should be resized.
    How It Works:
    • realloc() adjusts the size of the memory block that was previously allocated (using malloc(), calloc(), or realloc()).
    • If the new size is smaller than the original, it truncates the data.
    • If the new size is larger, it allocates new memory and copies the existing data to the new memory block. If the memory block cannot be resized in place, realloc() returns a new memory address.
    • The pointer passed to realloc() may change if the memory block is moved to a different location.
    Example:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int* arr;
        size_t n = 5;
    
        // Allocate memory for 5 integers
        arr = (int*)malloc(n * sizeof(int));
        if (arr == NULL) {
            printf("Memory allocation failed.\n");
            return 1;
        }
    
        // Initialize the array
        for (size_t i = 0; i < n; i++) {
            arr[i] = i + 1;
        }
    
        // Resize the array to hold 10 integers
        n = 10;
        arr = (int*)realloc(arr, n * sizeof(int));
    
        if (arr == NULL) {
            printf("Memory reallocation failed.\n");
            return 1;
        }
    
        // Print the resized array (new elements will be uninitialized or garbage)
        for (size_t i = 0; i < n; i++) {
            printf("arr[%zu] = %d\n", i, arr[i]);
        }
    
        free(arr);  // Free allocated memory
        return 0;
    }
    

    Explanation:

    • The program initially allocates memory for an array of 5 integers using malloc().
    • It then resizes the array to hold 10 integers using realloc().
    • Note that after resizing, the newly allocated memory is not initialized. This could lead to garbage values in the new elements, and you should initialize them if needed.

    Why Use realloc()?

    • You can resize dynamically allocated memory blocks at runtime.
    • It’s especially useful for cases like dynamically expanding an array as more elements are added.

    2. goto Statement

    The goto statement is used for unconditional branching in C. It allows the program to jump to a specific label within the function. However, goto should be used cautiously, as it can make code harder to read and maintain.

    Syntax:

    goto label;
    ...
    label: 
        // Code to jump to
    
    • label: A user-defined label where the program control will jump.
    • The goto statement is often used for error handling or breaking out of deeply nested loops.

    Example: Using goto for Error Handling

    #include <stdio.h>
    
    int main() {
        int num1 = 10, num2 = 0;
        int result;
    
        // Simple division with error handling using goto
        if (num2 == 0) {
            printf("Error: Division by zero!\n");
            goto end;  // Jump to the end of the program
        }
    
        result = num1 / num2;
        printf("Result: %d\n", result);
    
    end:
        printf("Program ended.\n");
        return 0;
    }
    

    Explanation:

    • In this example, goto is used to jump to the end label when a division by zero is detected, effectively avoiding further execution of the code after the error is caught.
    • It provides an easy way to exit from the code if a critical error occurs.

    Disadvantages of goto:

    • It can lead to "spaghetti code," where the program flow becomes difficult to follow.
    • Modern C programming practices generally prefer structured control flow statements like if, for, while, and switch, instead of goto.
    • It should be used sparingly and only in situations where it significantly improves code clarity, such as in error handling.

    Summary Table

    Concept Description Example Use Case
    calloc() Allocates memory for an array of elements, initializing them to zero. Used when you need zero-initialized memory.
    realloc() Resizes an existing memory block to a new size. Used to dynamically resize an array or memory block.
    goto Provides an unconditional jump to a labeled part of the program. Used for error handling or breaking out of nested loops.
    Disadvantages of goto Makes the code harder to read and maintain; often leads to "spaghetti code." Avoid using unless absolutely necessary.

    Conclusion

    Dynamic memory allocation using calloc() and realloc() is essential for managing memory efficiently in C programs. calloc() is useful when you need initialized memory, while realloc() allows resizing dynamically allocated memory. On the other hand, the goto statement can be used for direct program flow control, but it should be used sparingly, as it can complicate the readability of your code. For most cases, structured control flow statements should be preferred over goto.

    ← Previous topic 36
    Suffixes for Integer and Floating-Point Literals, Signal Handling
    Next topic 38 →
    Advance Topics: Self-Referential Structures, Linked Lists

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.3kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals