简体   繁体   中英

Memory Management : scope and local pointer variable

Memory Management : scope and local pointer variable

Q. In terms of Memory Management, What is the error in the following code?

 char* secret_message()
 {
   char message_buffer[100];
   char* text = "Hey man!";
   int n = 0;
   while (text[n] != '\0')
     n++;
   for (int i = 0; i <= n ; i++)
     message_buffer[i] = text[i];
   return message_buffer;
 }

Answer. I think message_buffer is local variable that is automatically reclaimed after function ends. This function returns a reference to an invalid memory location , since message_buffer disappears right after return statement.

Is it correct?

Please let me know. Thanks,

Answer. I think message_buffer is local variable that is automatically reclaimed after function ends. This function returns a reference to an invalid memory location , since message_buffer disappears right after return statement.

Yes, it is correct. message_buffer is allocated on stack, its memory will be deallocated when the function exits. the pointer will points to release memory.

BTW:

char* text = "Hey man!";

should be

const char* text = "Hey man!";

in modern C++.

message_buffer is automatic variable whose scope is within the function only. this variable either should be declared in main function or declared as static variable within the function.

You are correct. This produces undefined behaviour.

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