0

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.

Harsha
  • 3
  • 3
  • 1
    You modify `ptr`, but not `arr`. – ikegami Mar 22 '21 at 16:03
  • 1
    Function arguments in C are *copies* of what are passed, so modifying them will not affect what are passed. You should pass *pointers to what should be modified* when you want functions to modify caller's local things. – MikeCAT Mar 22 '21 at 16:03
  • `arr` is no longer valid, and you have reallocated memory that cannot be `free`d. Another solution is to change the function definition and `return` the new pointer value, so that you call as `arr = add(arr, i+1, i+1);` – Weather Vane Mar 22 '21 at 16:05
  • The linked question did not state that C always passes by value, and it did not provide any solution. It was not a duplicate. There are surely duplicates, but that wasn't it. – ikegami Mar 22 '21 at 16:06
  • Does this answer your question? [How do I modify a pointer that has been passed into a function in C?](https://stackoverflow.com/questions/766893/how-do-i-modify-a-pointer-that-has-been-passed-into-a-function-in-c) – Ian Abbott Mar 22 '21 at 16:25

1 Answers1

0

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
Antonin GAVREL
  • 9,682
  • 8
  • 54
  • 81