5 /* According to some resources, some implementations of malloc are
6 reluctant to allocate objects with a size larger than half the
7 range of the maximum size, perhaps due to internal overflows in
11 # define SEGMENT_LIMIT (SIZE_MAX / 2)
13 # define SEGMENT_LIMIT (((size_t)(-1)) / 2)
16 #define INITIAL_SIZE 16
18 typedef struct stack_segment
{
20 size_t allocated_size
;
22 struct stack_segment
*next
;
25 stack_segment
*head
= NULL
;
27 static stack_segment
*new_seg(stack_segment
* link_target
)
29 stack_segment
*seg
= calloc(1, sizeof (stack_segment
));
31 seg
->allocated_size
= INITIAL_SIZE
;
32 seg
->stack_data
= malloc(INITIAL_SIZE
* sizeof (int));
34 seg
->next
= link_target
;
43 void stack_push(int val
)
45 if (head
->head_idx
>= head
->allocated_size
) {
46 if (head
->allocated_size
* 2 > SEGMENT_LIMIT
) {
49 head
->allocated_size
*= 2;
51 realloc(head
->stack_data
, head
->allocated_size
* sizeof (int));
55 head
->stack_data
[head
->head_idx
++] = val
;
60 stack_segment
*new_head
;
62 if (head
->head_idx
== 0) {
64 * this behavior is undefined. Is interpreted as 'exit'
66 if (head
->next
== NULL
)
69 new_head
= head
->next
;
70 free(head
->stack_data
);
75 return head
->stack_data
[--head
->head_idx
];