gpt4 book ai didi

c - 新程序员来了,这个堆栈程序有什么问题吗?

转载 作者:行者123 更新时间:2023-11-30 21:21:00 26 4
gpt4 key购买 nike

当我执行它时,该函数不起作用,为什么?

#include<stdio.h>

struct stack{

int x[10];

int last;
};

void init(struct stack *s)
{

s->last=0;
}

void insert(struct stack *s)
{
int a;

while(a!=0)
{
int i;
printf("Enter the value\n");

scanf("%d",&i);

s->last++;

s->x[s->last]=i;
printf("%d",s->x[s->last]);
printf("enter 1 to continue 0 to exit\n");
scanf("%d",&a);

}
}

int main()
{

struct stack s;

int y,z;

printf("Trying out stacks\n");

printf("\n______________\n");

init(s);

insert(s);

return 0;

}

最佳答案

在函数insert()中,您声明了

int a;

然后在不初始化a的情况下,您将执行以下操作,

while(a!=0)

将给出Undefined Behaviour .

以下几行可能会导致缓冲区溢出,

s->last++; 
s->x[s->last]=i; // no restriction applied on last

last 可以超过 9,这可能会导致缓冲区溢出,如 x[10]

关于c - 新程序员来了,这个堆栈程序有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31031768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com