char *myfunc() {
char *temp = "string";
return temp;
}
In this piece of code, where does the allocation of the object pointed to by temp
happen and what would be its scope?
Is this function a valid way to return a char* pointer?
C dynamic memory allocation refers to performing manual memory management for dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely malloc, realloc, calloc and free.
Objects Memory Allocation in C++The way memory is allocated to variables and functions of the class is different even though they both are from the same class. The memory is only allocated to the variables of the class when the object is created. The memory is not allocated to the variables when the class is declared.
Objects are allocated directly from a thread local heap. A new object is allocated from this cache without needing to grab the heap lock. All objects less than 512 bytes (768 bytes on 64-bit JVMs) are allocated from the cache. Larger objects are allocated from the cache if they can be contained in the existing cache.
When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator. Use the delete[] operator to delete an array allocated by the new operator.
Is the code correct?
Yes your code is (almost) fine, because "string"
is a string literal and located in static storage.
Note: A pointer is just a variable which stores a memory address. This line simply stores the address of the string literal "string" inside a variable called temp
.
char *temp = "string";
The C++ standard guarantees that the string literal will stay in memory for the duration of the program as defined below. Which means you are free to use that memory address in any scope anywhere during the whole life of your program.
Why?
The C++03 standard (current) has this to say:
An ordinary string literal has type “array of n const char” and static storage duration (3.7),
And section 3.7.1 - 1:
All objects which neither have dynamic storage duration nor are local have static storage duration. The storage for these objects shall last for the duration of the program.
Warning:
In your code you are returning a char*
, you should really be returning a const char *
. It is undefined behavior if you try to modify a string literal, and your function return value shouldn't pretend to allow it.
On a related side note to the warning. If you have in your code in 2 different places a string called "string"
then whether or not they are distinct strings is implementation defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With