what's going wrong here with realloc()?

75 Views Asked by At

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.

1

There are 1 best solutions below

0
Antonin GAVREL On BEST ANSWER

A few things:

  • First, you should pass your array by reference with &. You pass your pointer by value which has no effect.

  • Second, you forgot to make your realloc with sizeof(int), equivalent to 4.

  • Third, you have to assign your value the following way: *(*(ptr) + len - 1) = ele;

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