0

I have a struct that looks like this:

typedef struct
{
        int *numberList;
        int size;
        int maxNumber;
} list;

Then I have this method to create a list:

list* createList(int maxNumber)
{
    list l;
    l.size = 0;
    l.numberList = malloc(maxNumber*sizeof(int));
    list* ptr = &l;
    return ptr;
}

Then I have this method in the works:

int updateSize(list *ls)
{
    ls->size++;
    printf("This is a print statement.\n");

    return 0;
}

I check the value of size in my main method and it works fine for both initialization and the update, but when it gets to the print statement, size changes to a large incorrect number (garbage value?), e.g. 4196190 instead of 1. In the full version of my code I also use malloc() in my updateSize() for my numberList and even that keeps the results as they should be up until the print statement. My question is: What is it about the print statement that alters the member(s) of my struct?

Rez
  • 187
  • 12

1 Answers1

4

You return the address of l from createList, but l is local to that function, so the space it occupies can (and apparently, is) used for other things, overwriting what was there before.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101