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] != '')
     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.

链接地址: http://www.djcxy.com/p/36340.html

上一篇: 本地变量的c ++内存管理内存分配

下一篇: 内存管理:范围和本地指针变量