0

I have a question regarding dynamic allocation.

Why do the array values change after using realloc? It works fine if the initial size of the array is greater than the next size (e.g. 10 20) but if the initial size of the array is lesser than the next size (e.g. 20 10), the code gives me garbage values.

The code works properly in local side but when I try it on online compilers, it does not work the way it's supposed to.

Is there anything wrong with my code? Or is it a problem with online compilers? And am I using the realloc function properly?

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

void print(int *ptr, int size);
void reallocate(int *ptr, int size);
void assign(int *ptr, int size);

int main(void) {

    int n;
    // Set initial size for array
    scanf("%d",&n);
    int *arr = (int*) malloc(n * sizeof(int));

    // Assign values from 0 to n-1
    assign(arr, n);
    // Print values assigned
    print(arr, n);
    printf("\n");

    // Set new size for reallocation
    scanf("%d",&n);
    reallocate(arr, n);
    // Assign values again
    assign(arr, n);
    // Print values
    print(arr,n);

    return 0;
}

// Prints values of the array
void print(int *ptr, int size) {
    for(int i = 0; i < size; i++) printf("%d ",ptr[i]);
}

// Reallocates new size for array
void reallocate(int *ptr, int size) {
    ptr = realloc(ptr, size*sizeof(int));
}

// Assigns values from 0 to n-1
void assign(int *ptr, int size) {
    for(int i = 0; i < size; i++) ptr[i] = i;
}

I hope for your responses.

John Cymmer
  • 195
  • 1
  • 9
  • 1
    Parametets in C are passed by copy. So in `reallocate` you just discard the new pointer returned by the `realloc`, while you continue using the now invalid pointer outside of that function. – Blaze Mar 02 '20 at 14:52
  • You need to return the pointers from those functions. – Lundin Mar 02 '20 at 14:52
  • Hint: what does `void f(int i) {i=5;} int main() {int x=7; f(x); printf("%d\n", x);}` do? – user253751 Mar 02 '20 at 14:52
  • Why create reallocate instead of realloc? –  Mar 02 '20 at 16:01

0 Answers0