C realloc

Created By: chatGPT

In C, realloc is a standard library function used to adjust the size of a previously allocated memory block. It is helpful when you need to increase or decrease the size of an array or any dynamically allocated memory but want to keep the existing data intact. The syntax for realloc is as follows:
void *realloc(void *ptr, size_t size);
ptr is a pointer to the memory block that you want to resize, and size is the new size in bytes. If ptr is NULL, realloc behaves like malloc, allocating a new block of memory of the specified size.
int *arr = (int *)malloc(5 * sizeof(int));
Now, if you want to change the size of this array to hold 10 integers, you can use realloc as follows:
arr = (int *)realloc(arr, 10 * sizeof(int));
If the reallocation is successful, it returns a pointer to the newly allocated memory, which may be the same as the old pointer or a new one. If it fails, it returns NULL but does not free the original memory block, so it's crucial to check for NULL before assigning the new pointer back.
if (arr == NULL) {
    // Handle memory allocation failure
}
Here is a complete example demonstrating the use of realloc:
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int i;
    
    arr = (int *)malloc(5 * sizeof(int));
    for (i = 0; i < 5; i++) {
        arr[i] = i + 1; // Initialize with some values
    }
    
    // Resize the array to hold 10 integers
    arr = (int *)realloc(arr, 10 * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    
    // Assign new values to the newly allocated space
    for (i = 5; i < 10; i++) {
        arr[i] = i + 1;
    }
    
    // Print the values in the array
    for (i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }
    
    free(arr); // Don't forget to free the memory
    return 0;
}
Introduction And SetupVariablesData TypesIntFloatDoubleCharVoidUnsignedSignedConstantsEnumerationsArraysStringsStructsUnionsTypedefsPointersDynamic Memory AllocationMallocCallocReallocFreeFunctionsFunction DeclarationsFunction DefinitionsFunction CallsReturn StatementInline FunctionsRecursionHeader FilesPreprocessor DirectivesControl FlowIf StatementElse StatementElse If StatementSwitch StatementCase StatementDefault CaseLoopsFor LoopWhile LoopDo While LoopBreak StatementContinue StatementGoto StatementLabelsOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsConditional (ternary) OperatorComma OperatorSizeof OperatorData StructuresLinked ListsStacksQueuesTreesGraphsFunction PointersCallbacksMacrosCommentsSingle Line CommentsMulti Line CommentsSyntaxSyntax ErrorsCompilation ErrorsDebuggingStandard Input OutputPrintfScanfFile HandlingFopenFcloseFreadFwriteFprintfFgetsFputsError HandlingErrnoAssertionsExit FunctionExit CodesEvent HandlingSignal HandlingInterrupts