0

I am unsure if I am using the realloc function correctly.

In my program, I first ask the user for the size of the array and allocate memory for it using malloc, then initialise it with some values.

Then I want to make the same array twice it's size, using realloc. Here is my code. Am I using realloc to resize int *A correctly?

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

int main(){
  int n;
  printf("Enter size of array\n");
  scanf("%d", &n);

  int *A = (int*)malloc(n*sizeof(int));     //dynamically allocated array
  for (int i = 0; i < n; i++)               //assign values to allocated memory
  { 
    A[i] = i + 1;
  }

  A = (int*)realloc(A, 2*sizeof(int));     //make the array twice the size
  free(A);
}
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Ivan Lendl
  • 87
  • 1
  • 2
  • 8

2 Answers2

1
  • When using malloc() , don't cast the return value as said here
  • You are not using the right size. In hereint *A = (int*)malloc(n*sizeof(int)); the size given to malloc is n*sizeof(int). If you want twice that size, you should call realloc() with n*sizeof(int)*2 instead of 2*sizeof(int)
  • Handle realloc() failure. In case realloc(A, new_size) fails, A == NULL and you will have memory leak. So, use a different pointer B, check if (B != NULL) and then assign A = B (old_size = new_size). If B == NULL deal with the allocation fail
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • 2
    And third bullet: • You should not use the notation `old_ptr = realloc(old_ptr, new_size);` because it leaks memory when `realloc()` fails. Use `void *new_ptr = realloc(old_ptr, new_size); if (new_ptr != 0) { old_ptr = new_ptr; old_size = new_size; } else { …deal with memory allocation failure… }`. – Jonathan Leffler May 28 '17 at 05:44
  • 1
    @JonathanLeffler I'll add this, but did you intentionally use _void*_ instead of OP _int*_? – CIsForCookies May 28 '17 at 05:50
  • 2
    Yes (it was intentional), but using `int *` also works. Since `realloc()` returns a `void *`, assigning to a `void *` is hardly a crime — it defers the type conversion to the assignment. Using `int *new_ptr = realloc(…)` does the type conversion with the return value. Both are valid; use whichever you prefer. – Jonathan Leffler May 28 '17 at 05:52
  • @Lendl you are now using the right size, but you're still casting: _int *A = (int*)malloc(n*sizeof(int));_ – CIsForCookies May 28 '17 at 06:24
  • 1
    fixed that as well. – Ivan Lendl May 28 '17 at 06:27
1

In this case it's easier to double the n before malloc so you don't have the use realloc, because you know, that you gonna double the arraysize. Using realloc can slow the working of the program, because if you make it longer, and the adresses after the currently allocated memories aren't free, then the whole array will be moved. Also you have the change the last line as it was suggested before me.

Urudin
  • 286
  • 2
  • 14