0

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 Answers3

2

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

taocp
  • 23,276
  • 10
  • 49
  • 62
2

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.

Narendra Bista
  • 279
  • 1
  • 2
  • 6
0

You are correct. This produces undefined behaviour.

Muscles
  • 471
  • 4
  • 12