0
votes

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,

3
Yes, it is just as you assume.Nbr44

3 Answers

2
votes

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++.

2
votes

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.

0
votes

You are correct. This produces undefined behaviour.