realloc 触发了一个断点

  • 本文关键字:一个 断点 realloc c
  • 更新时间 :
  • 英文 :


我的程序有问题,我已经用C实现了一个简单的堆栈 问题是,当我第二次尝试重新分配堆栈数组时,程序会在 Realloc 函数内部触发一个 brekapoint,我不知道可能出了什么问题,因为我正在使用缓冲区来检查 Realloc 是否失败。 可能,这段代码是我使用 Realloc 函数的地方:

struct stack {
void** data;
int top;
int initial_size;
};
static void stack_resize(struct stack* instance, int capacity)
{
if (instance->initial_size == instance->top)
{
int new_sz = capacity * sizeof *instance->data;
// THIS REALLOC crashes
void** buffer = realloc(instance->data, new_sz); // realloc the stack array
printf("reallocating memoryn");
if (buffer) {
instance->data = buffer;
instance->initial_size = new_sz;
}
}
}

以下函数是调用stack_resize((的地方

void stack_push(struct stack* instance, void* data)
{
if (instance->top >= instance->initial_size)
{
// shrink the array
stack_resize(instance, instance->initial_size);
}
instance->data[++instance->top] = data;
printf("pushing onto the stack!n");
}

这是我初始化所有数据的构造函数。

struct stack* stack_new(int initial_size)
{
struct stack* new_stack = (struct stack*)malloc(sizeof(struct stack));
if (!new_stack) {
fprintf(stderr, "no memory available from the operative systemn");
return NULL;
}
memset(new_stack, 0, sizeof(struct stack));
new_stack->data = (void**)malloc(sizeof(void*) * initial_size);
if (!new_stack->data) {
fprintf(stderr, "could not allocate memory for the buffern");
return NULL;
}
printf("created a stack with %d slot(s)n", initial_size);
new_stack->top = -1;
new_stack->initial_size = initial_size;
return new_stack;
}

这是程序的入口点:

int main(int argc, char** argv)
{
struct stack* new_stack = stack_new(2);
for (int i = 0; i < 55; i++)
{
stack_push(new_stack, (void*)i);
}
getchar();
return 0;
}

任何帮助将不胜感激!谢谢大家。

崩溃是因为您正在将new_sz分配给instance->initial_size。 因为new_sz以字节为单位保存数组的实际大小,这capacity*sizeof(void *)

int new_sz = capacity * sizeof *instance->data;
instance->initial_size = new_sz;

您的堆栈topinitial_size将不匹配。

if (instance->top >= instance->initial_size)

您的top将始终小于initial_size,并且您不会分配新内存。

为了使程序正常工作,您需要进行以下更改。

int new_sz = (capacity+1) * sizeof(void *);
instance->initial_size = capacity+1;//instead of new_size

最新更新