Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

arrays - C - Avoiding warning "address of stack memory associated with local variable returned"

I've written the following simple program that sums up the numbers from 0 to 9:

#include <stdio.h>
#include <stdlib.h>

int* allocArray() {
    int arr[10];
    return arr;
}

int main(void){
    int* p;
    int summe = 0;
    p = allocArray();
    for(int i = 0; i != 10; ++i) {
        p[i] = i;
    }
    for(int i = 0; i != 10; ++i) {
        summe += p[i];
    }
    printf("Sum = %d
", summe);
}

The code compiles and delivers the expected result "45". However I get the following warning: 'address of stack memory associated with local variable 'arr' returned'. What am I doing wrong?

question from:https://stackoverflow.com/questions/65848290/c-avoiding-warning-address-of-stack-memory-associated-with-local-variable-ret

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is undefined behaviour, plain and simple. The only reason it "works" is because with this particular compiler the stack hasn't been trashed yet, but it is living on borrowed time.

The lifetime of arr ends immediately when the function call is complete. After that point any pointers to arr are invalidated and cannot be used.1

Your compiler uses stack memory to store local variables, and the warning indicates that you're returning an address to a now-invalidated stack variable.

The only way to work around this is to allocate memory dynamically and return that:

int* allocArray() {
    int* arr = calloc(10, sizeof(int));

    return arr;
}

Where you're now responsible for releasing that memory later.

You can also use static to extend the lifetime of arr:

int* allocArray() {
    static int arr[10];

    return arr;
}

Though this is not without consequences, either, as now arr is shared, not unique to each function call.


1 Like a lot of things in C there's significant overlap between what you "cannot do" because they lead to undefined behaviour and/or crashes and what you "can do" because it's permitted by the syntax and compiler. It's often your responsibility to know the consequences of any code you write, implied or otherwise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...