Bruno Mello
Bruno Mello

Reputation: 4618

Calling a function changes value of another pointer

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

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409442

You have two problems (at least):

  1. 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.

  2. 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

Related Questions