c - 如果调用 push 函数超过 8 次,为什么我的代码会崩溃?

标签 c stack stack-overflow

//每当我将 push 的函数调用次数增加超过 8 次时,它就会在一切正常之前崩溃。需要您的帮助。在下面的代码中,我创建了一个使用动态数组的堆栈程序,请记住,只要堆栈被填满,就不应使用 realloc 函数将值加倍,从而导致堆栈溢出。

#include<stdio.h>
#include<stdlib.h>
#include<memory.h>
typedef struct ArrayStack
{
int top;
int capacity;
int *arr;
}*stack;

stack Creation()
{
 stack S;
 S=(stack)malloc(sizeof(struct ArrayStack));
 if(!S)return NULL;
 S->top=-1;
 S->capacity=1;
 S->arr=(int*)malloc(S->capacity*sizeof(int));
 if(!S->arr)return NULL;
 return S;
}
int is_Full(stack S)
{
return S->top==S->capacity-1;
}
int is_Empty(stack S)
{
return S->top==-1;
}

void Doubling(stack S)
{
 S->capacity*=2;
 S->arr=realloc(S->arr,S->capacity);
}

void push(stack S,int data)
{
if(is_Full(S)) 
Doubling(S);

S->arr[++S->top]=data;
}

int pop(stack S)
{
if(is_Empty(S))
printf("\nStack underflow");
else
return S->arr[S->top--];
}

int main()
{
stack S;
int i=0,size=9;
S=Creation();
**for(i=0;i<size;i++)
push(S,19+1);**   // As in this case

return 0;
}

最佳答案

S->arr = malloc(S->capacity * sizeof(int));
S->arr = realloc(S->arr, S->capacity);

您仅为 S->capacity/sizeof(int) 项重新分配足够的空间。

关于c - 如果调用 push 函数超过 8 次,为什么我的代码会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14881984/

相关文章:

我们可以在 c 中使用 system() 更新运行时值吗

Java:面向对象设计;链表和栈

c++:使用throw,try and catch

c# - 表达式评估 - 避免 StackOverflow 异常

Javascript 奇怪的 StackOverflow 错误

c# - 数组中的反射和递归 - StackOverflowException

java - 递归最大堆栈溢出错误

c++ - 如何在 Windows 7 中安装 MinGW 64 位

当客户端断开连接时,C 服务器停止响应

c - 使用指针显示数组内容