下列函数返回的指针不是不可访问的吗?

char *foo(int rc)
{
    switch (rc)
    {
        case 1:

            return("one");

        case 2:

            return("two");

        default:

            return("whatever");
    }
}

因此,C/C++中局部变量的生存期实际上只在函数中,对吗?这意味着,在char* foo(int)终止后,它返回的指针不再有任何意义,对吗?

我对局部变量的生存期有点困惑.什么是好的澄清?

推荐答案

是的,局部变量的生存期在创建它的范围内({}).

局部变量具有自动或本地存储.Automatic,因为一旦创建它们的范围结束,它们就会自动销毁.

然而,这里有一个字符串文本,它是在实现定义的只读内存中分配的.字符串文字不同于局部变量,它们在程序的整个生命周期中都是活动的.它们有static duration[Ref 1]生命周期 .

A word of caution!

However, note that any attempt to modify the contents of an string literal is an undefined behavior (UB). User programs are not allowed to modify contents of a string literal.
Hence, it is always encouraged to use a const while declaring a string literal.

const char*p = "string"; 

而不是

char*p = "string";    

事实上,在C++中,声明不使用const而不在C中声明字符串文字,但是,用const声明字符串文字给了您编译器在您试图修改第二种情况下字符串字符串时的警告的优势.

100:

#include<string.h> 
int main() 
{ 
    char *str1 = "string Literal"; 
    const char *str2 = "string Literal"; 
    char source[]="Sample string"; 
 
    strcpy(str1,source);    // No warning or error just Uundefined Behavior 
    strcpy(str2,source);    // Compiler issues a warning 
 
    return 0; 
} 

Output:

cc1: warnings being treated as errors
prog.c: In function ‘main’:
prog.c:9: error: passing argument 1 of ‘strcpy’ discards qualifiers from pointer target type

请注意,编译器会针对第二种情况发出警告,但不会针对第一种情况发出警告.


要回答这里的几个用户提出的问题,请执行以下操作:

What is the deal with integral literals?

换句话说,以下代码有效吗?

int *foo()
{
    return &(2);
} 

答案是,不,这个代码无效.它的格式不正确,将导致编译器错误.

比如:

prog.c:3: error: lvalue required as unary ‘&’ operand
     

String literals are l-values, i.e: You can take the address of an string literal, but cannot change its contents.
However, any other literals (int,float,char, etc.) are r-values (the C standard uses the term the value of an expression for these) and their address cannot be taken at all.


[Ref 1]C99 standard 6.4.5/5 "String Literals - Semantics":

在转换阶段7中,将值为零的字节或代码附加到由字符串文字或文字产生的每个多字节字符序列.The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence美元.对于字符串文字,数组元素具有char类型,并且使用多字节字符序列的单个字节进行初始化;对于宽字符串文字,数组元素具有wchar_t类型,并且使用宽字符序列进行初始化.

如果这些数组的元素具有适当的值,则这些数组是否是不同的,这一点尚不明确.If the program attempts to modify such an array, the behavior is undefined

C++相关问答推荐

如何判断宏参数是否为C语言中的整型文字

如何创建由符号组成的垂直结果图形?

变量>;-1如何在C中准确求值?

如何跨平台处理UTF-16字符串?

每个 struct 变量在C中都有自己的命名空间吗?

如何在CANbus RX/TX FIFO起始地址寄存器(ATSAME 51)的特定地址初始化数组?

为什么我从CSV文件中进行排序和搜索的代码没有显示数据的所有结果?

如何在POSIX-UEFI中获得输入?

使用Open62541向OPCUA服务器发送读请求时内存泄漏

从BIOS(8086)中读取刻度需要多少?

将 struct 数组写入二进制文件时发生Valgrind错误

如何逐位读取二进制文件?

向左移位3如何得到以字节为单位的位数?

发送和接收的消息中的Unix域套接字不匹配

C语言中的指针和多维数组

未为同一文件中的函数执行DirectFunctionCall

memcmp 是否保证按顺序比较字节?

全局变量 y0 与 mathlib 冲突,无法编译最小的 C 代码

无法在线程内用 C 打印?

nullptr_t 是否会 destruct 类型双关或指针转换?