简体   繁体   中英

Preventing memory leaks in C

I know that I need to free all mallocs, callocs and reallocs. But what variables need to be free() also?

static my_struct *ms;
int x = 0;

some_other_struct *do_something (some_other_struct *sos) {
    third_struct *ts;
    my_struct *ms2;
    int y = 10;
    //....
    return sos;
}

Which variables do I need to free here? Do local variables free() themselves automatically?

Local variables do not free() themselves automatically, but you must not free() them either since they are located on the stack and not on the heap. After a function returns, the stack pointer is incremented and the local variables of this function stop to exist, ie the memory they have occupied on the stack may be overwritten in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM