[英]Segfault on realloc in 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 :
root@ab# ./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)
在重新分配中,您未能包含
* sizeof(int)
部分,因此您沒有重新分配足夠的內存。
您忘記在realloc()中乘以sizeof(int)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.