ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›Dynamic Memory Allocation: calloc and realloc, goto
    Programming FundamentalsTopic 37 of 39

    Dynamic Memory Allocation: calloc and realloc, goto

    7 minread
    1,261words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,261
      Code examples0
      DifficultyIntermediate