如何使用realloc(奇怪的行为)

时间:2016-10-12 05:16:19

标签: c realloc

所以我有一个程序,它的工作正常。

#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;
}

但如果我改变功能&#39;推&#39;使用realloc而不是malloc和free,程序崩溃与消息&#34; `./t' ;:realloc()出错:下一个大小无效:0x0000000001031030 中止&#34;

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;    
}    

还有valgrind打印消息&#39;无效的写入大小8&#39;当我尝试使用realloc时。 我做错了什么? 我使用gcc和Debian Jessie x86_64。

1 个答案:

答案 0 :(得分:1)

您将错误的尺码传递给realloc。因此,您的程序很快就会遇到未定义的行为。

使用:

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