Home > front end >  Program is terminating after it reaches realloc() function
Program is terminating after it reaches realloc() function

Time:07-15

I am a beginner coder in C and I recently learned the concept of dynamic arrays using calloc/malloc in C but I seem to have ran in a program.

This program right here asks for 10 elements from the user and then asks if you want to add more into it? depending on the value entered, realloc function is supposed to reallocate more memory for further elements, but the code just terminates when it reaches the realloc statement. Please help.

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

int* arr;
size_t arrSize = 10;

int main(){
int modSize;
printf("The Program is making a dynamic array\n");
arr = calloc(arrSize,sizeof(int));
if(arr == NULL){
    printf("error from calloc\n");
}
printf("Enter Values for the Array: \n");
for(int i=0; i<arrSize;   i){
    scanf("%d",&arr[i]);
}

printf("Would you like to add more values? If yes type the amount : ");
scanf("%d",&modSize);

arrSize  = modSize;
arr = realloc(arrSize,arrSize*sizeof(int));
if(arr == NULL){
    printf("error from realloc\n");
}

for(int i = 10; i<arrSize;   i){
    scanf("%d",&arr[i]);
}

for(int i = 0; i<arrSize;   i){
    printf("%d\t",arr[i]);
}

free(arr);
return 0;
}

output

CodePudding user response:

Your compiler should have told you that:

<source>:23:15: error: invalid conversion from 'size_t' {aka 'long unsigned int'} to 'void*' [-fpermissive]
   23 | arr = realloc(arrSize,arrSize*sizeof(int));
      |               ^~~~~~~
      |               |
      |               size_t {aka long unsigned int}

The first argument to realloc is the memory to reallocate, not a size:

void *realloc( void *ptr, size_t new_size );

Parameters

  • ptr - pointer to the memory area to be reallocated
  • new_size - new size of the array in bytes

In other words,

arr = realloc(arr, arrSize*sizeof(int));

is more correct, but please do turn on all errors and warnings in your compiler settings and heed them.

  • Related