2017-07-16 30 views
0

我有一個結構,看起來像這樣:C:爲什麼print語句會改變我的struct成員的值?

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

然後,我有這樣的方法來創建一個列表:

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

然後我在作品中這個方法:

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?

+0

順便說一下,'l.maxNumber'沒有分配。 – chux

回答

4

You return the address of lcreateList,但l是該函數的本地對象,所以它佔據的空間可以(並且顯然是)被用於其他事物,覆蓋之前存在的內容。

相關問題