美好的一天,我需要你的帮助来解决这个问题。我做了一个copystack函数,当我从控制台输入数据时它会弹出,我收到下一条消息错误SIGSEGV(段错误)错误,但是当我从代码中输入数据时不会弹出,我留下了堆栈和copystack函数的输入数据的代码。
/* declaracion */
struct tpila{
int clave;
struct tpila *sig;
}; //Stack type
void crear(struct tpila **pila) //Creation of stack function
{ *pila = (struct tpila *) malloc(sizeof(struct tpila));
(*pila)->sig = NULL;
}
int vacia(struct tpila *pila){
return (pila->sig == NULL);
}
void apilar(struct tpila *pila, int elem){ //Stack input function
struct tpila *nuevo;
nuevo = (struct tpila *) malloc(sizeof(struct tpila));
nuevo->clave = elem;
nuevo->sig = pila->sig;
pila->sig = nuevo;
}
void desapilar(struct tpila *pila, int *elem){
struct tpila *aux;
aux = pila->sig;
*elem = aux->clave;
pila->sig = aux->sig;
free(aux);
}
void mostrar(struct tpila *pila)//Function print stack
{
struct tpila *aux;
aux=pila->sig;
while(aux!=NULL)
{
printf("%d->",aux->clave);
aux=aux->sig;
}
printf("NULL\n");
}
void copiarPila(struct tpila *pila1,struct tpila *pila2)//Copystack function
{
struct tpila *pila_aux,*aux;
aux=pila1->sig;
//Llenamos la pila auxiliar
while(aux!=NULL)
{
apilar(pila_aux,aux->clave);
aux=aux->sig;
}
//Colocamos los datos de la pila auxiliar en la pila 2
aux=pila_aux->sig;
while(aux!=NULL)
{
apilar(pila2,aux->clave);
aux=aux->sig;
}
}
int main(void)
{
struct tpila *pila1,*pila2;
bool ingresar_datos=true;
int dato;
int desicion=2;
//Creation of stack 1 a stack 2
crear(&pila1);
crear(&pila2);
printf("Title\n");
printf("-----------------------------------------------\n");
//Colocamos valores a la pila1
while(ingresar_datos)
{
printf("Input a number\n");
scanf("%d",&dato);
printf("\n");
apilar(pila1,dato);//Input variable dato
printf("To stop input numbers press 2 \n");
scanf("%d",&desicion);
system("cls");
if(desicion==2)
{
ingresar_datos=false;
}
}
printf("Show stack 1 1\n");
mostrar(pila1);
printf("-----------------------------------------------\n");
printf("Show stack 2 2\n");
mostrar(pila2);
printf("-----------------------------------------------\n");
printf("Copy stack 1 to stack 2\n");
copiarPila(pila1,pila2);----->In this part the program marks the problem
printf("-----------------------------------------------\n");
printf("Show stack 2 \n");
mostrar(pila2);
printf("-----------------------------------------------\n");
system("pause");
}
最佳答案
问题
正如您提到的,问题从这里开始
copiarPila(pila1,pila2);
在此函数中,您声明了一个指向结构体的指针,并传递了未初始化的指针。
struct tpila *pila_aux;
apilar( pila_aux ,aux->clave);
在函数apilar
中,您正在访问未初始化的内存并在那里写入
nuevo->sig = pila->sig;
pila->sig = nuevo;
这会导致未定义的行为和程序可能崩溃。
<小时/>解决方案
只需为struct tpila *pila_aux
分配内存,访问/修改其内容后就不会得到SIGSEGV
。不要忘记释放这个指针。
struct tpila *pila_aux = malloc(sizeof(struct tpila));
struct tpila *aux;
// ...
// Do stuff here ...
// ...
free(pila_aux);
<小时/>
你也应该知道
- Why dont cast mallocs return value
- 用英语编写程序源代码是一种很好的做法,即使它只适合您,尤其是当您要在某个地方发布时。
关于c - dev c++ 堆栈算法中的 SIGSEGV(段错误)错误(Lenguage c),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45738242/