我编写了一个相当简单(ish)的堆栈实现,如果需要,它会自动增长其内部数组缓冲区。
为此,我自然会使用realloc - 它可以工作,但是,所有数组元素在 realloc() 调用之后都是反向排序的。
有问题的代码:
此示例将触发所述行为:
#include "pd/strlib.h"
#include "pd/stack.h"
#include "pd/memory.h"
#include <stdlib.h>
#include <stdio.h>
int main()
{
int index = 0;
char* buffer;
pd_stack_t* stc = pd_stack_new();
pd_stack_push(stc, "blue");
pd_stack_push(stc, "green");
pd_stack_push(stc, "red");
pd_stack_push(stc, "yellow");
pd_stack_push(stc, "pink");
pd_stack_push(stc, "olive");
pd_stack_push(stc, "beige");
pd_stack_push(stc, "gold");
pd_stack_push(stc, "grey");
pd_stack_push(stc, "lime");
pd_stack_push(stc, "khaki");
while((index++) != 500)
{
pd_stack_push(stc, "__random_value__");
}
buffer = (char*)malloc(pd_stack_size(stc));
pd_stack_dump_tomem(stc, buffer, 1);
fprintf(stdout, "%s", buffer);
return 0;
}
我真的对此一无所知。请帮忙!