我有以下代码,您可以尝试使用c99 filename.c; ./a.out
#include <stdio.h>
#include <stdlib.h>
typedef unsigned long long int se_t; // stack element type
se_t stack_size = 0;
se_t *bottom_of_stack = NULL;
#define top_of_stack (bottom_of_stack + stack_size * sizeof(se_t))
#define stack_infix(op) stack_push(stack_pop() #op stack_pop())
#define do_times(x) for(int _i=0; _i<x; _i++)
void stack_push(se_t v) {
bottom_of_stack = realloc(bottom_of_stack,
++stack_size * sizeof(se_t));
*top_of_stack = v;
}
void stack_print() {
printf("stack(%d): \n", (int)stack_size);
for(se_t *i = bottom_of_stack;
i <= top_of_stack;
i += sizeof(se_t)) {
printf("%p: %d \n", (void*)i, (int)*i);
}
}
int main() {
int i = 2;
do_times(3) {
stack_push(i*=i);
stack_print();
}
}
每次推送东西时我都会重新分配堆栈。这是输出(带有我的评论):
stack(1):
0x105200820: 0 // realloc successfully allocated some memory for the first time
0x105200860: 4
stack(2):
0x105200820: 0 // extended the memory range without moving it somewhere else
0x105200860: 4
0x1052008a0: 16
stack(3):
0x105200830: 0 // reallocated the memory to some other region (see the address)
0x105200870: 0 // and failed for some reason to copy the old data!
0x1052008b0: 0 // why?!
0x1052008f0: 256
答案 0 :(得分:4)
指针算法已使用sizeof (basetype)
。当你这样做
#define top_of_stack (bottom_of_stack + stack_size * sizeof(se_t))
你有效地乘以sizeof (se_t)
两次。
如果bottom_of_stack
的值为0xF000
且stack_size
为2且sizeof (se_t)
为0x10
bottom_of_stack + stack_size == 0xF020
bottom_of_stack + stack_size * sizeof (se_t) == 0xF400 /* or whatever */
答案 1 :(得分:2)
使用此:
#define top_of_stack (bottom_of_stack + (stack_size - 1))
实际上,您将数据存储在已分配空间的末尾。
哦,并改变这一行:
i += sizeof(se_t)) {
应该是:
i++) {
由于pmg
关于指针算术的说法。