Search code examples
crealloc

Heap block at ... modified at ... past requested size of 4


Edit: Turns out problem is at 15.line, i should have written counter-1 inside the brackets.

I should note that upcoming is a bonus question i have been asked for a new grad student level job so please only point out where am i making the mistake.

Hello, I'm trying to write a simple C code with this algorithm,

  1. Enter a number
  2. From a given list, try to imitate the number
  3. Print out used numbers and the difference between given and immitated number
  4. Also a rule about minimum and maximum value for the input

So I did this for the given task (it isn't done yet but my aim is not getting a problem within debugger for now);

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

uint16_t AvailableValues[10] = {50,100,150,250,400,500,600,750,850,1000};
int* divider(int number)
{
    int counter=1,i=9;
    int* array;
    array=(int*)malloc(counter*sizeof(int));
    while (i)
    {
        while(number/AvailableValues[i]>0)
        {
            printf ("%d %d %d\n",number,counter,i);
            array[counter]=AvailableValues[i];
            number-=AvailableValues[i];
            counter++;
            array=realloc(array,counter*sizeof(int));
        }
        i--;
    }
    if (number)
    {
        array[counter]=number;
    }
    return array;
}

int main()
{
    int number=0,total=0;
    int* list;
    printf ("Please enter a new target value:");
    scanf ("%d",&number);
    for (int i=0;i<10;i++)
    {
        total+=AvailableValues[i];
    }
    while (!(number>=AvailableValues[0] && number<=total))
    {
        printf ("Please enter a new target value:");
        scanf ("%d",&number);
    }
    list=divider(number);
    printf("Solution List");
    printf("-------------");
    for (int j=0;j<sizeof(list);j++)
    {
        printf("S[%d]:%d",j,list[j]);
    }
    return 0;
}

Problem is, whenever it hits realloc for the second time (i can get one printf on the console) it returns the "Heap block at ... modified at ... past requested size of 4". I have yet to find the reason of it and I'm not good with the pointers so i can't say if the problem is pointer (int* array) or anything else. What is wrong with the reallocation and how can i fix the problem?


Solution

  • array[counter]=AvailableValues[i];
    

    in this line you access the element which is one past the last element of the allocated space.

    You need:

    array[counter - 1]=AvailableValues[i];