Reputation: 4618
I have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXNOME 60
typedef struct Periodo
{
char nome[MAXNOME];
struct Periodo *nextPeriodo;
} periodo;
void getNomePeriodo(char *nomePeriodo){
printf("Type name: ");
scanf("%s", nomePeriodo);
return;
}
void getMenuHeader(){
printf("\n\n");
}
void insertPeriodo(periodo **basePeriodo){
periodo novoPeriodo;
getNomePeriodo(novoPeriodo.nome);
novoPeriodo.nextPeriodo = NULL;
periodo *itrPeriodo = *basePeriodo;
while(itrPeriodo->nextPeriodo!=NULL){
itrPeriodo = itrPeriodo->nextPeriodo;
}
itrPeriodo->nextPeriodo = &novoPeriodo;
printf("OK!\n");
return;
}
int main(){
int *opcaoMenu = malloc(sizeof(int));
periodo *basePeriodo = malloc(sizeof(periodo));
insertPeriodo(&basePeriodo);
printf("%p\n", (basePeriodo)->nextPeriodo->nextPeriodo);
getMenuHeader();
printf("%p\n", (basePeriodo)->nextPeriodo->nextPeriodo);
return 0;
}
Basically the problem I'm facing is that it looks like the value of (basePeriodo)->nextPeriodo->nextPeriodo
is changing when I call the function getMenuHeader
, the output I am having is this:
Type name: 2020
OK!
(nil)
0x7ffe9dd7d840
I would expect that the value of (basePeriodo)->nextPeriodo->nextPeriodo
would be the same independent of the function call and it would be NULL as it is before function but I have no idea why it changes after I call it, could someone explain why this is happening?
Upvotes: 0
Views: 28
Reputation: 409442
You have two problems (at least):
The structure **basePeriodo
is uninitialized and its members will be indeterminate. That includes the pointer nextPeriodo
which might not be NULL
. This will make the loop in insertPeriodo
maybe iterate out into unallocated memory, leading to undefined behavior.
When you fix this problem, novoPeriodo
is a local variable inside the insertPeriodo
function. Once the function returns the life-time of novoPeriodo
ends and any pointers to novoPeriodo
will become invalid. That means the assignment
itrPeriodo->nextPeriodo = &novoPeriodo;
is invalid, and also lead to undefined behavior if you use this pointer after the function returns.
The common solution is to dynamically allocate the node structure.
Upvotes: 2