Kin*_*es 1 c stack realloc segmentation-fault dynamic-memory-allocation
我编写了一个简单的程序来实现基于动态数组的堆栈。realloc已用于调整我用来存储堆栈元素的容器的大小。
#include <stdio.h>
#include <stdlib.h>
void stack_push(int **stack, int *stackSize, int element);
int stack_pop(int **stack, int *stackSize);
int main()
{
char ch;
int *stack = NULL, stackSize = 0;
do
{
printf("\n1. Push\n");
printf("2. Pop\n");
printf("Exit (0)\n");
printf("Enter choice : ");
scanf("%c", &ch);
switch(ch)
{
case '1':
stack_push(&stack, &stackSize, 1);
break;
case '2':
printf("%d\n", stack_pop(&stack, &stackSize));
break;
case '0':
break;
}
} while (ch != '0');
return 0;
}
void stack_push(int **stack, int *stackSize, int element)
{
if (!*stack)
{
*stack = malloc(sizeof(int));
}
else
{
*stack = realloc(*stack, sizeof(int) * (*stackSize + 1));
}
*stack[*stackSize] = element;
*stackSize += 1;
}
int stack_pop(int **stack, int *stackSize)
{
if (!*stack)
{
return -1;
}
else
{
*stackSize -= 1;
int element = *stack[*stackSize];
if (*stackSize > 0)
{
*stack = realloc(*stack, sizeof(int) * (*stackSize));
}
else
{
free(*stack);
*stack = NULL;
}
return element;
}
}
Run Code Online (Sandbox Code Playgroud)
该程序对于第一个元素运行良好。但是当我尝试添加后续元素时,我遇到了分段错误。
我尝试调试我的代码,发现:
线路上发生分段错误:
*stack[*stackSize] = element;
Run Code Online (Sandbox Code Playgroud)
这是显示其他详细信息的屏幕截图: Segmentation Failure
我哪里出错了?
这是一个优先级问题。改变:
*stack[*stackSize] = element;
Run Code Online (Sandbox Code Playgroud)
到:
(*stack)[*stackSize] = element;
Run Code Online (Sandbox Code Playgroud)
还改变:
int element = *stack[*stackSize];
Run Code Online (Sandbox Code Playgroud)
到:
int element = (*stack)[*stackSize];
Run Code Online (Sandbox Code Playgroud)