重新分配已触发断点

时间:2018-08-12 10:03:05

标签: 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 memory\n");

        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 system\n");
        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 buffer\n");
        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;
}

任何帮助将不胜感激!感谢所有人。

1 个答案:

答案 0 :(得分: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