简体   繁体   中英

c language and some doubts of pointer

#include<stdio.h>
#include<stdlib.h>
char* re()
{
    char *p = "hello";
    return p;      
}
int main()
{
    char* tem = re();
    printf("%s", tem);
    return 0;
}

my compiler is Dev-C++. I think that when the function of 're' completes, the pointer of 'p' will be deleted and the stack space which 'p' havs pointed to also will be deleted. So the pointer of 'tem' can not visit the stack space which the 'p' points to. In my opinions, this code will appear some bugs. but why not?

This problem distorts me a long time. If you can tell me the reason, i will appreciate your kind heart.

p does not point to a stack space. It points to the string literal "hello" . Since string literals are guaranteed to be valid at the whole program, your program is OK.

(I don't know about Dev-C++, but in most compilers, string literals are allocated in some read-only memory at the loading of the program, and stays there until the end of it)

Edit: note that even if the string was on the stack, and the code was really buggy, nothing in the language guarantee that is will not work. invalid memory can (but not have to) still contain the value it contained before being invalid.

The string "hello" is not stack alloc'ed (but char *p pointer is).
It is in the 'data segment' because it's a constant value (read-only memory).
From C FAQ: http://c-faq.com/decl/strlitinit.html

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