Home > Blockchain >  Using realloc() to increase size of array when even number is typed (from function)
Using realloc() to increase size of array when even number is typed (from function)

Time:10-13

hi im trying to make my array increase its size with realloc from function when even number is typed, but the compiler is displying Segmentation Fault whatever number I type.Any ideas how can i fix this?

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


int MakeArray(int n,int *ptr)
{
    ptr = (int*) malloc(n*sizeof(int));
    if(ptr==NULL)
    {
        puts("Allocation failed");
    }
    return *ptr;
}


int ReAllocArray(int n,int *ptr)
{
    ptr = (int*) realloc(ptr,n*sizeof(int));
      if(ptr==NULL)
    {
        puts("Reallocation failed");
    }
    return *ptr;
}


int main() {
    int n;
    int *ptr=NULL;
    puts("Enter size of n");
    scanf("%d",&n);
MakeArray(n,ptr);
    puts("Entering even number is increasing the size of the array by 1");
    for(int i =0;i<n;  i)
    {
        scanf("%d",&ptr[i]);
        if(ptr[i]%2==0)
        {
              n;
            ReAllocArray(n,ptr);
        }
    }
    puts("Your array is:");
    for(int i =0;i<n;i  )
    {
        printf("%d",ptr[i]);
    }
    return 0;
}

CodePudding user response:

You need to pass pointer to pointer to int to modify it or/and return the reference to the allocated memory

int *MakeArray(size_t n, int **ptr)
{
    if(ptr)
    {
        *ptr = malloc(n*sizeof(**ptr));
        if(!*ptr)
        {
            puts("Allocation failed");
        }
    }
    return *ptr;
}

Same when you realloc

int *ReAllocArray(size_t n, int **ptr)
{
    int *tmp = NULL;
    if(ptr)
    {
        tmp = realloc(*ptr,n * sizeof(**ptr));
        if(!tmp)
        {
            puts("Reallocation failed");
        }
        else
        {
            *ptr = tmp;
        }
    }
    return tmp;
}

When you call it you need to pass pointer to pointer:

MakeArray(n,&ptr);
ReAllocArray(n,&ptr);

It would be worth checking what those functions return to know if allocations succeeded.

Also:

  1. Use the correct type for sizes (size_t nor int)
  2. Do not cast the result of malloc/realloc. If it does not compiler you are using the wrong (C ) compiler to compile the C code.
  3. Use objects not types in sizeofs
  4. When realloc use a temporary variable. Otherwise, you may have a memory leak

BTW you do not need the MakeArray function at all as realloc will work fine when you pass NULL pointer (it will simple not copy any data to the allocated memory)

  •  Tags:  
  • c
  • Related