當使用加倍stratigy即時得到一個賽格故障第二次調整的realloc ..這是爲什麼......段錯誤的realloc的用C
code :
stack.c :
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>
#include "stack.h"
/* Allocate the fields inside the stack */
void stackNew(my_stack* s){
s->alloc_length = STACKSIZE;
s->logical_length = 0;
s->elems = malloc(STACKSIZE * sizeof(int)); // creates 4 int boxes to store the ints
assert(s->elems != NULL);
}
/* Free the Heap memory, if allocated any */
void stackDispose(my_stack* s){
free(s->elems);
}
/* Push new elements into the stack */
void stackPush(my_stack* s,int data){
if(s->alloc_length <= s->logical_length){ // If the alloclength and the logicallength are the same, then we may need to resize it
s->alloc_length *= 2; // Doubling stratgie
printf("\n Reallocated : size : %d \n",s->alloc_length);
s->elems = realloc(s->elems,s->alloc_length);
assert(s->elems != NULL);
}
printf("alloc : %d logical : %d \n",s->alloc_length,s->logical_length);
s->elems[s->logical_length] = data;
s->logical_length++;
}
/* Pop the elements out of the stack */
int stackPop(my_stack* s){
s->logical_length--;
if(s->logical_length <= 0){
printf("\n cannot pop!! stack is empty!! \n");
return 2;
}
return s->elems[s->logical_length];
}
void stackDisplay(my_stack* s){
int i = 0;
for(i = 0; i < s->logical_length; i++){
printf("\n s->elems : %d \n",(s->elems[i]));
}
}
/* Main */
int main(){
my_stack stack;
int pop;
printf("\n Begin!! \n");
stackNew(&stack);
stackPush(&stack,10);
stackPush(&stack,20);
stackPush(&stack,30);
stackPush(&stack,40);
stackPush(&stack,50);
stackPush(&stack,60);
stackPush(&stack,70);
stackPush(&stack,80);
stackPush(&stack,90);
stackPush(&stack,100);
stackDisplay(&stack);
pop = stackPop(&stack);
printf("\n Popping!! - %d \n",pop);
pop = stackPop(&stack);
printf("\n Popping!! - %d \n",pop);
pop = stackPop(&stack);
printf("\n Popping!! - %d \n",pop);
pop = stackPop(&stack);
printf("\n Popping!! - %d \n",pop);
pop = stackPop(&stack);
printf("\n Popping!! - %d \n",pop);
pop = stackPop(&stack);
printf("\n Popping!! - %d \n",pop);
stackDisplay(&stack);
stackDispose(&stack);
printf("\n End!! \n");
return 0;
}
stack.h :
typedef struct __my_stack{
int* elems;
int logical_length;
int alloc_length;
}my_stack;
#define STACKSIZE 4
void stackNew(my_stack* s);
void stackDispose(my_stack* s);
void stackPush(my_stack* s,int data);
int stackPop(my_stack* s);
output :
[email protected]# ./a.out
Begin!!
alloc : 4 logical : 0
alloc : 4 logical : 1
alloc : 4 logical : 2
alloc : 4 logical : 3
Reallocated : size : 8
alloc : 8 logical : 4
alloc : 8 logical : 5
alloc : 8 logical : 6
alloc : 8 logical : 7
Reallocated : size : 16
*** Error in `./a.out': realloc(): invalid next size: 0x0000000000986010 ***
Aborted (core dumped)
這已經是MCV的例子嗎? http://stackoverflow.com/help/mcve。如果你能削減這個問題並提出一個真正的問題,這可能會有所幫助。 – Marged