Aleksei Udalov Aleksei Udalov - 1 month ago 21
C Question

How to use realloc (strange behavior)

So I have a program and its work fine.

#include <stdio.h>
#include <stdlib.h>
#define STACKDEFSIZE 1
typedef struct
{
unsigned long int maxsize;
unsigned long int cursize;
unsigned long int* arr;
} stack;

stack* create_stack()
{
stack* res = (stack*)malloc(sizeof(stack));
res->arr = malloc(sizeof(long) * STACKDEFSIZE);
res->maxsize = STACKDEFSIZE;
res->cursize = 0;
return res;
}

void push(stack* st, int val)
{
if (st->cursize == st->maxsize)
{
unsigned long int* old = st->arr;
st->maxsize *= 2;
st->arr = malloc(sizeof(unsigned long int) * st->maxsize);
int i;
for(i = 0; i < st->cursize; i++)
st->arr[i] = old[i];
free(old);
}
st->arr[st->cursize] = val;
st->cursize += 1;
}

int main() {
stack* s = create_stack();
int i;
for(i = 0; i < 10000; i++)
{
push(s, i);
}
return 0;
}


But if I change function 'push' to use realloc instead of malloc and free, program crash with message " Error in `./t': realloc(): invalid next size: 0x0000000001031030
Aborted"

void push(stack* st, int val)
{
if (st->cursize == st->maxsize)
{
st->maxsize *= 2;
st->arr = realloc(st->arr, st->maxsize);
}
st->arr[st->cursize] = val;
st->cursize += 1;
}


Also valgrind print message 'Invalid write of size 8' when I trying to use realloc.
What I doing wrong?
I use gcc and Debian Jessie x86_64.

Answer

You are passing the wrong size to realloc. As a consequence, your program runs into undefined behavior in no time.

Use:

st->arr = realloc(st->arr, sizeof(*st->arr)*st->maxsize);
Comments