字符串在C中的“生命时间”

时间:2022-11-20 22:27:26

Wouldn't the pointer returned by the following function inaccessible?

后不会返回的指针函数访问?

char *foo( int rc ) 
{
    switch (rc) 
    {
      case 1:           return("one");
      case 2:           return("two");
      default:           return("whatever");
    }
}

So the lifetime of a local variable in C/C++ is practically only within the function, right? Which means, after char* foo(int) terminates, the pointer it returns no longer means anything?

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

I'm a bit confused about lifetime of local var. Could anyone give me a good clarification?

我有点困惑于当地var的一生。有人能给我一个好澄清吗?

9 个解决方案

#1


76  

Yes, lifetime of an local variable is within the scope({,}) in which it is created.
Local variables have automatic or local storage.
Automatic because they are automatically destroyed once the scope within which they are created ends.

是的,一生局部变量的范围内({ })中创建的。局部变量自动或本地存储。自动,因为他们会自动销毁一旦范围内创建它们。

However, What you have here is an string literal, which is allocated in an implementation defined read only memory. String literals are different from local variables and they remain alive throughout the program lifetime.They have static duration [Ref 1] lifetime.

然而,这是一个字符串,分配在一个实现定义只读存储器。字符串文字不同于本地变量和他们仍然活在整个项目生命周期。他们有静态时间(参考1)一生。

A word of caution!
However, note that any attempt to modify the contents of an string literal is an Undefined Behavior. 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。

const char*p = "string"; 

instead of,

相反的,

char*p = "string";    

In fact, in C++ it is deprecated to declare a string literal without the const though not in c. However, declaring a string literal with a const gives you the advantage that compilers would usually give you a warning in case you attempt to modify the string literal in second case.

事实上,在c++中声明一个字符串是弃用没有const虽然不是C。然而,声明一个字符串常量提供了优势,编译器通常会给你一个警告如果你试图修改第二个案例中的字符串。

Sample program:

示例程序:

#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

警告被视为错误prog。c:在函数“main”中:prog。c:9:错误:从指针目标类型中传递“strcpy”的参数1

Notice the compiler warns for the second case but not for the first.

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


EDIT: To answer the Q being asked by a couple of users here:

编辑:回答几个用户提出的问题:

What is the deal with integral literals?
In other words is this code valid:

积分文字是怎么处理的?换句话说,该代码是否有效:

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

The answer is, No this code is not valid, it is ill-formed & will give an compiler error.
Something like:

答案是,不,这段代码无效,它格式不正确,会导致编译错误。喜欢的东西:

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 it's contents.
However, any other literals(int,float,char etc) are r-values(c standard uses the term the value of an expression for these) & their address cannot be taken at all.

字符串常量是l值i。e:你可以取字符串文字的地址,但不能改变它的内容。但是,任何其他文字(int、float、char等)都是r值(c标准使用这些文字的表达式的值这个词),而且它们的地址根本不能取。


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

[Ref 1]C99标准6.4.5/5 "String Literals - semantic ":

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence; for wide string literals, the array elements have type wchar_t, and are initialized with the sequence of wide characters...

在翻译阶段7中,一个字节或值零的代码被附加到每个多字节字符序列中,这些序列是由字符串文字或文字产生的。然后使用多字节字符序列初始化静态存储持续时间和长度足以包含序列的数组。对于字符串字面值,数组元素具有类型char,并使用多字节字符序列的单个字节初始化;对于宽字符串文本,数组元素具有wchar_t类型,并使用宽字符序列初始化…

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

如果这些数组的元素具有适当的值,则不确定这些数组是否不同。如果程序试图修改这样的数组,则该行为未定义。

#2


74  

It's valid, string literals have static storage duration, so the pointer is not dangling.

它是有效的,字符串文本具有静态存储时间,因此指针不会悬空。

For C, that is mandated in section 6.4.5, paragraph 6:

对于C,这是在第6.4.5节中规定的,第6段:

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.

在翻译阶段7中,一个字节或值零的代码被附加到每个多字节字符序列中,这些序列是由字符串文字或文字产生的。然后使用多字节字符序列初始化静态存储持续时间和长度足以包含序列的数组。

And for C++ in section 2.14.5, paragraphs 8-11:

对于第2.14.5节第8-11段中的c++,

8 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

8个普通字串和UTF-8字串字串也称为窄字串字串。窄字符串文本具有“n const char数组”类型,其中n是下面定义的字符串大小,具有静态存储时间(3.7)。

9 A string literal that begins with u, such as u"asdf", is a char16_t string literal. A char16_t string literal has type “array of n const char16_t”, where n is the size of the string as defined below; it has static storage duration and is initialized with the given characters. A single c-char may produce more than one char16_t character in the form of surrogate pairs.

以u开头的字符串文字,如u"asdf",是char16_t字符串文字。一个char16_t字符串文字具有类型“n const char16_t数组”,其中n为下面定义的字符串的大小;它具有静态存储时间,并使用给定的字符初始化。一个c-char可以生成多个char16_t字符(代理对的形式)。

10 A string literal that begins with U, such as U"asdf", is a char32_t string literal. A char32_t string literal has type “array of n const char32_t”, where n is the size of the string as defined below; it has static storage duration and is initialized with the given characters.

10始于你的字符串,如U“asdf”,是char32_t字符串文字。char32_t字符串文字类型“char32_t“n常量数组,其中n是字符串的大小如下定义;静态存储时间和初始化与给定的字符。

11 A string literal that begins with L, such as L"asdf", is a wide string literal. A wide string literal has type “array of n const wchar_t”, where n is the size of the string as defined below; it has static storage duration and is initialized with the given characters.

11 L开头的字符串,如L“asdf”,是一种宽字符串文字。宽字符串类型“n const wchar_t的数组”,其中n是字符串的大小如下定义;静态存储时间和初始化与给定的字符。

#3


14  

String literals are valid for the whole program (and are not allocated not the stack), so it will be valid.

字符串常量对于整个程序都是有效的(并且不是分配给堆栈的),所以它是有效的。

Also, string literals are read-only, so (for good style) maybe you should change foo to const char *foo(int)

另外,字符串文字是只读的,所以(为了好的风格)也许你应该把foo改为const char *foo(int)

#4


6  

Good question. In general, you would be right, but your example is the exception. The compiler statically allocates global memory for a string literal. Therefore, the address returned by your function is valid.

好问题。一般来说,你是对的,但是你的例子是个例外。编译器静态地为字符串文本分配全局内存。因此,函数返回的地址是有效的。

That this is so is a rather convenient feature of C, isn't it? It allows a function to return a precomposed message without forcing the programmer to worry about the memory in which the message is stored.

这是C的一个非常方便的特性,不是吗?它允许一个函数返回一个预合成的消息,而不会强迫程序员担心消息被存储的内存。

See also @asaelr's correct observation re const.

参见@asaelr的正确观察。

#5


5  

Yes, it is valid code, case 1 below. You can safely return C strings from a function in at least these ways:

是的,这是有效的代码,下面是案例1。您可以通过以下方式安全地从函数返回C字符串:

  • const char* to a string literal. Can't be modified, must not be freed by caller. Rarely useful for the purpose of returning a default value, because of the freeing problem described below. Might make sense if you actually need to pass a function pointer somewhere, so you need a function returning a string..

    const char *字符串文字。不能修改,不能被调用者释放。很少用于返回一个默认值的目的,因为下面描述的释放问题。实际上是有意义的,如果你需要通过一个函数指针,所以你需要一个函数返回一个字符串。

  • char* or const char* to static char buffer. Must not be freed by caller. Can be modified (either by caller if not const, or by the function returning it), but a function returning this can't (easily) have multiple buffers, so not (easily) thread safe, and caller may need to copy the returned value before calling the function again.

    char*或const char*到静态char缓冲区。不能被调用者释放。可以修改(如果不是const,可以由调用者修改,也可以由函数返回),但是返回这个的函数不能(容易地)有多个缓冲区,因此不(容易地)线程安全,调用者可能需要在再次调用函数之前复制返回的值。

  • char* to a buffer allocated with malloc. Can be modified, but must usually be explicitly freed by caller, and has the heap allocation overhead. strdup is of this type.

    将char*分配给malloc的缓冲区。可以修改,但必须由调用者显式释放,并具有堆分配开销。strdup就是这种类型的。

  • const char* or char* to a buffer, which was passed as an argument to the function (returned pointer does not need to point to the first element of argument buffer). Leaves responsibility of buffer/memory management to caller. Many standard string functions are of this type.

    const char*或char*到一个缓冲区,该缓冲区作为参数传递给函数(返回的指针不需要指向参数缓冲区的第一个元素)。将缓冲区/内存管理的责任留给调用方。许多标准字符串函数都属于这种类型。

One problem is, mixing these in one function can get complicated. Caller needs to know how it should handle the returned pointer, how long it is valid, and if caller should free it, and there's no (nice) way of determining that at runtime. So you can't for example have a function, which sometimes returns a pointer to a heap-allocated buffer which caller needs to free, and sometimes a pointer to a default value from string literal, which caller must not free.

一个问题是,把它们混合在一个函数中会变得很复杂。调用者需要知道它应该如何处理返回的指针,它的有效时间,以及调用者是否应该释放它,并且在运行时没有(很好的)方法来确定它。例如,你不能有一个函数,它有时返回一个指针,指向调用者需要释放的heap分配的缓冲区,有时返回一个指针,指向字符串文字的默认值,调用者不能释放这个值。

#6


3  

Local variables are only valid within the scope they're declared, however you don't declare any local variables in that function.

局部变量仅在声明的范围内有效,但是在该函数中不声明任何局部变量。

It's perfectly valid to return a pointer to a string literal from a function, as a string literal exists throughout the entire execution of the program, just as a static or a global variable would.

从函数返回指向字符串文字的指针是完全有效的,因为字符串文字在整个程序执行过程中都存在,就像静态或全局变量一样。

If you're worrying about what you're doing might be invalid undefined, you should turn up your compiler warnings to see if there is in fact anything you're doing wrong.

如果你担心你正在做的事情可能是无效的,你应该打开你的编译器警告,看看你做错了什么。

#7


1  

str will never be dangling pointer. Because it points to static address where string literals resides . It will be mostly readonly and global to the program when it will be loaded . Even if you try to free or modify ,it will throw segmentation fault on platforms with memory protection .

str永远不会是悬浮指针。因为它指向字符串常量所在的静态地址。当程序加载时,它将主要是只读和全局的。即使您尝试释放或修改,它也会在具有内存保护的平台上抛出分割错误。

#8


0  

A local variable is allocated on the stack. After the function finishes, the variable goes out of scope and is no longer accessible in the code. However, if you have a global (or simply - not yet out of scope) pointer that you assigned to point to that variable, it will point to the place in the stack where that variable was. It could be a value used by another function, or a meaningless value.

在堆栈上分配一个本地变量。函数完成后,变量超出范围,在代码中不再可访问。但是,如果您有一个全局(或仅仅是还没有超出范围)指针,您将其分配给指向该变量,它将指向堆栈中该变量所在的位置。它可以是另一个函数使用的值,也可以是无意义的值。

#9


0  

In the above example shown by you, you are actually returning the allocated pointers to whatever function that calls the above. So It would not become a local pointer. And moreover the pointers that are needed to be returned, memory is allocated in global segment.

在上面的示例中,您实际上是将分配的指针返回给调用上述函数的任何函数。所以它不会变成一个本地指针。而且,需要返回的指针,内存是在全局段中分配的。

Thanking You,

感谢你,

Viharri P L V.

Viharri P L V。

#1


76  

Yes, lifetime of an local variable is within the scope({,}) in which it is created.
Local variables have automatic or local storage.
Automatic because they are automatically destroyed once the scope within which they are created ends.

是的,一生局部变量的范围内({ })中创建的。局部变量自动或本地存储。自动,因为他们会自动销毁一旦范围内创建它们。

However, What you have here is an string literal, which is allocated in an implementation defined read only memory. String literals are different from local variables and they remain alive throughout the program lifetime.They have static duration [Ref 1] lifetime.

然而,这是一个字符串,分配在一个实现定义只读存储器。字符串文字不同于本地变量和他们仍然活在整个项目生命周期。他们有静态时间(参考1)一生。

A word of caution!
However, note that any attempt to modify the contents of an string literal is an Undefined Behavior. 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。

const char*p = "string"; 

instead of,

相反的,

char*p = "string";    

In fact, in C++ it is deprecated to declare a string literal without the const though not in c. However, declaring a string literal with a const gives you the advantage that compilers would usually give you a warning in case you attempt to modify the string literal in second case.

事实上,在c++中声明一个字符串是弃用没有const虽然不是C。然而,声明一个字符串常量提供了优势,编译器通常会给你一个警告如果你试图修改第二个案例中的字符串。

Sample program:

示例程序:

#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

警告被视为错误prog。c:在函数“main”中:prog。c:9:错误:从指针目标类型中传递“strcpy”的参数1

Notice the compiler warns for the second case but not for the first.

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


EDIT: To answer the Q being asked by a couple of users here:

编辑:回答几个用户提出的问题:

What is the deal with integral literals?
In other words is this code valid:

积分文字是怎么处理的?换句话说,该代码是否有效:

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

The answer is, No this code is not valid, it is ill-formed & will give an compiler error.
Something like:

答案是,不,这段代码无效,它格式不正确,会导致编译错误。喜欢的东西:

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 it's contents.
However, any other literals(int,float,char etc) are r-values(c standard uses the term the value of an expression for these) & their address cannot be taken at all.

字符串常量是l值i。e:你可以取字符串文字的地址,但不能改变它的内容。但是,任何其他文字(int、float、char等)都是r值(c标准使用这些文字的表达式的值这个词),而且它们的地址根本不能取。


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

[Ref 1]C99标准6.4.5/5 "String Literals - semantic ":

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence; for wide string literals, the array elements have type wchar_t, and are initialized with the sequence of wide characters...

在翻译阶段7中,一个字节或值零的代码被附加到每个多字节字符序列中,这些序列是由字符串文字或文字产生的。然后使用多字节字符序列初始化静态存储持续时间和长度足以包含序列的数组。对于字符串字面值,数组元素具有类型char,并使用多字节字符序列的单个字节初始化;对于宽字符串文本,数组元素具有wchar_t类型,并使用宽字符序列初始化…

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

如果这些数组的元素具有适当的值,则不确定这些数组是否不同。如果程序试图修改这样的数组,则该行为未定义。

#2


74  

It's valid, string literals have static storage duration, so the pointer is not dangling.

它是有效的,字符串文本具有静态存储时间,因此指针不会悬空。

For C, that is mandated in section 6.4.5, paragraph 6:

对于C,这是在第6.4.5节中规定的,第6段:

In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.

在翻译阶段7中,一个字节或值零的代码被附加到每个多字节字符序列中,这些序列是由字符串文字或文字产生的。然后使用多字节字符序列初始化静态存储持续时间和长度足以包含序列的数组。

And for C++ in section 2.14.5, paragraphs 8-11:

对于第2.14.5节第8-11段中的c++,

8 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

8个普通字串和UTF-8字串字串也称为窄字串字串。窄字符串文本具有“n const char数组”类型,其中n是下面定义的字符串大小,具有静态存储时间(3.7)。

9 A string literal that begins with u, such as u"asdf", is a char16_t string literal. A char16_t string literal has type “array of n const char16_t”, where n is the size of the string as defined below; it has static storage duration and is initialized with the given characters. A single c-char may produce more than one char16_t character in the form of surrogate pairs.

以u开头的字符串文字,如u"asdf",是char16_t字符串文字。一个char16_t字符串文字具有类型“n const char16_t数组”,其中n为下面定义的字符串的大小;它具有静态存储时间,并使用给定的字符初始化。一个c-char可以生成多个char16_t字符(代理对的形式)。

10 A string literal that begins with U, such as U"asdf", is a char32_t string literal. A char32_t string literal has type “array of n const char32_t”, where n is the size of the string as defined below; it has static storage duration and is initialized with the given characters.

10始于你的字符串,如U“asdf”,是char32_t字符串文字。char32_t字符串文字类型“char32_t“n常量数组,其中n是字符串的大小如下定义;静态存储时间和初始化与给定的字符。

11 A string literal that begins with L, such as L"asdf", is a wide string literal. A wide string literal has type “array of n const wchar_t”, where n is the size of the string as defined below; it has static storage duration and is initialized with the given characters.

11 L开头的字符串,如L“asdf”,是一种宽字符串文字。宽字符串类型“n const wchar_t的数组”,其中n是字符串的大小如下定义;静态存储时间和初始化与给定的字符。

#3


14  

String literals are valid for the whole program (and are not allocated not the stack), so it will be valid.

字符串常量对于整个程序都是有效的(并且不是分配给堆栈的),所以它是有效的。

Also, string literals are read-only, so (for good style) maybe you should change foo to const char *foo(int)

另外,字符串文字是只读的,所以(为了好的风格)也许你应该把foo改为const char *foo(int)

#4


6  

Good question. In general, you would be right, but your example is the exception. The compiler statically allocates global memory for a string literal. Therefore, the address returned by your function is valid.

好问题。一般来说,你是对的,但是你的例子是个例外。编译器静态地为字符串文本分配全局内存。因此,函数返回的地址是有效的。

That this is so is a rather convenient feature of C, isn't it? It allows a function to return a precomposed message without forcing the programmer to worry about the memory in which the message is stored.

这是C的一个非常方便的特性,不是吗?它允许一个函数返回一个预合成的消息,而不会强迫程序员担心消息被存储的内存。

See also @asaelr's correct observation re const.

参见@asaelr的正确观察。

#5


5  

Yes, it is valid code, case 1 below. You can safely return C strings from a function in at least these ways:

是的,这是有效的代码,下面是案例1。您可以通过以下方式安全地从函数返回C字符串:

  • const char* to a string literal. Can't be modified, must not be freed by caller. Rarely useful for the purpose of returning a default value, because of the freeing problem described below. Might make sense if you actually need to pass a function pointer somewhere, so you need a function returning a string..

    const char *字符串文字。不能修改,不能被调用者释放。很少用于返回一个默认值的目的,因为下面描述的释放问题。实际上是有意义的,如果你需要通过一个函数指针,所以你需要一个函数返回一个字符串。

  • char* or const char* to static char buffer. Must not be freed by caller. Can be modified (either by caller if not const, or by the function returning it), but a function returning this can't (easily) have multiple buffers, so not (easily) thread safe, and caller may need to copy the returned value before calling the function again.

    char*或const char*到静态char缓冲区。不能被调用者释放。可以修改(如果不是const,可以由调用者修改,也可以由函数返回),但是返回这个的函数不能(容易地)有多个缓冲区,因此不(容易地)线程安全,调用者可能需要在再次调用函数之前复制返回的值。

  • char* to a buffer allocated with malloc. Can be modified, but must usually be explicitly freed by caller, and has the heap allocation overhead. strdup is of this type.

    将char*分配给malloc的缓冲区。可以修改,但必须由调用者显式释放,并具有堆分配开销。strdup就是这种类型的。

  • const char* or char* to a buffer, which was passed as an argument to the function (returned pointer does not need to point to the first element of argument buffer). Leaves responsibility of buffer/memory management to caller. Many standard string functions are of this type.

    const char*或char*到一个缓冲区,该缓冲区作为参数传递给函数(返回的指针不需要指向参数缓冲区的第一个元素)。将缓冲区/内存管理的责任留给调用方。许多标准字符串函数都属于这种类型。

One problem is, mixing these in one function can get complicated. Caller needs to know how it should handle the returned pointer, how long it is valid, and if caller should free it, and there's no (nice) way of determining that at runtime. So you can't for example have a function, which sometimes returns a pointer to a heap-allocated buffer which caller needs to free, and sometimes a pointer to a default value from string literal, which caller must not free.

一个问题是,把它们混合在一个函数中会变得很复杂。调用者需要知道它应该如何处理返回的指针,它的有效时间,以及调用者是否应该释放它,并且在运行时没有(很好的)方法来确定它。例如,你不能有一个函数,它有时返回一个指针,指向调用者需要释放的heap分配的缓冲区,有时返回一个指针,指向字符串文字的默认值,调用者不能释放这个值。

#6


3  

Local variables are only valid within the scope they're declared, however you don't declare any local variables in that function.

局部变量仅在声明的范围内有效,但是在该函数中不声明任何局部变量。

It's perfectly valid to return a pointer to a string literal from a function, as a string literal exists throughout the entire execution of the program, just as a static or a global variable would.

从函数返回指向字符串文字的指针是完全有效的,因为字符串文字在整个程序执行过程中都存在,就像静态或全局变量一样。

If you're worrying about what you're doing might be invalid undefined, you should turn up your compiler warnings to see if there is in fact anything you're doing wrong.

如果你担心你正在做的事情可能是无效的,你应该打开你的编译器警告,看看你做错了什么。

#7


1  

str will never be dangling pointer. Because it points to static address where string literals resides . It will be mostly readonly and global to the program when it will be loaded . Even if you try to free or modify ,it will throw segmentation fault on platforms with memory protection .

str永远不会是悬浮指针。因为它指向字符串常量所在的静态地址。当程序加载时,它将主要是只读和全局的。即使您尝试释放或修改,它也会在具有内存保护的平台上抛出分割错误。

#8


0  

A local variable is allocated on the stack. After the function finishes, the variable goes out of scope and is no longer accessible in the code. However, if you have a global (or simply - not yet out of scope) pointer that you assigned to point to that variable, it will point to the place in the stack where that variable was. It could be a value used by another function, or a meaningless value.

在堆栈上分配一个本地变量。函数完成后,变量超出范围,在代码中不再可访问。但是,如果您有一个全局(或仅仅是还没有超出范围)指针,您将其分配给指向该变量,它将指向堆栈中该变量所在的位置。它可以是另一个函数使用的值,也可以是无意义的值。

#9


0  

In the above example shown by you, you are actually returning the allocated pointers to whatever function that calls the above. So It would not become a local pointer. And moreover the pointers that are needed to be returned, memory is allocated in global segment.

在上面的示例中,您实际上是将分配的指针返回给调用上述函数的任何函数。所以它不会变成一个本地指针。而且,需要返回的指针,内存是在全局段中分配的。

Thanking You,

感谢你,

Viharri P L V.

Viharri P L V。