Search code examples
crealloc

Strange behaviour of realloc with certain values


I need to realloc an int array of initial dimension 5 with N values and fill them with the sum of previous values. Everything works well if N <= 6 but if I put N == 7, program crash with this error:

a.out: malloc.c:2403: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.

I do nothing special or strange, and I have no idea why I have this behaviour. This is my code:

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


int * change(int * arr, int n)
{
  int * a, i, somma = 0;

  a = realloc(arr, n * sizeof(int));

  for(i = 0; i < 5; i++)
    somma += arr[i];

  for(int j = i; j < (5+n); j++) {
    a[j] = somma;
    somma += a[j];
  }

  return a;
}

int main()
{
  int N, i, *arr, *arr1;

  arr = malloc(5 * sizeof(int));

  printf("give me 5 numbers\n");
  for(i = 0; i < 5; i++)
    scanf("%d", &arr[i]);

  printf("give me N number to use in realloc\n");
  scanf("%d", &N);

  arr1 = change(arr, N);

  for(i = 0; i < (5+N); i++) {
    printf("%d\n", arr1[i]);
  }

  return 0;
}

I realloc in a different pointer to avoid problem. Help are extremely usefull. Thanks


Solution

  • Here is a problem:

    a = realloc(arr, n * sizeof(int));
    
    for(i = 0; i < 5; i++)
      somma += arr[i];
    

    The realloc function invalidates the argument passed, arr. It causes undefined behaviour to use arr afterwards, as you do by writing arr[i].

    To fix this you could move the summation to before the realloc line.


    Another problem is that the next loop writes out of bounds:

    for(int j = i; j < (5+n); j++) {
        a[j] = somma;
    

    You only allocated space for n entries but then you loop up to 5+n. (And in main you loop up to 5+N too). Maybe you should realloc (5+n) entries instead.