cmallocdynamic-memory-allocationreallocmemory-reallocation

what's going wrong here with realloc()?


I am writing a code which uses realloc(). The following is a simplified version of the problem. Though the code looks obvious yet it doesn't seem to work.

// Program for implementing variable length integer array.

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

void add(int* ptr,int len,int ele){
    ptr = (int*)realloc(ptr,len);
    *(ptr+len-1) = ele;
}

void main(){
    
    int max_len = 10;
    
    int* arr = (int*)malloc(sizeof(int));
    
    for(int i=0;i<max_len;i++)
        add(arr,i+1,i+1);
    
    printf("The elements are...\n");
    
    for(int i=0;i<max_len;i++)
        printf("%d\n",*(arr+i));
}

The program runs for max_len=8 or low but not beyond it. Why is this happening? Thanks in advance.


Solution

  • A few things:

    See the corrected code below:

    #include<stdio.h>
    #include<stdlib.h>
    
    void add(int** ptr,int len,int ele){
        *ptr = (int*)realloc(*ptr,len*sizeof(int));
        *(*(ptr) + len - 1) = ele;
    }
    
    void main(){
    
        int max_len = 10;
    
        int* arr = (int*)malloc(sizeof(int));
    
        for(int i=0;i<max_len;i++)
            add(&arr,i+1,i);
    
        printf("The elements are...\n");
    
        for(int i=0;i<max_len;i++)
            printf("%d\n",arr[i]);
    }
    

    output:

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9