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.