3

Can reassigning a C style string cause a memory leak? Like so:

char * s = "Hello!";
s = "Hello, world!";

My question may appear as stupid, but please bear with me; I am currently still a dummie in C++.

In the second line of code, the C style string s is longer, so does it have it internally reallocate memory? Does this cause a memory leak? And do I have to call delete?

Thanks

sockfd2
  • 535
  • 1
  • 3
  • 9

3 Answers3

4

Actually, technically no. String literals are provided special static allocation. See

Is a string literal in c++ created in static memory?

Community
  • 1
  • 1
rileyberton
  • 485
  • 3
  • 5
3

Memory leak are caused by dynamic memory allocation.

There is no dynamic allocation here, so no memory leak.

Actually, string literals have static storage duration. The standard says (draft n3690):

3.7.1 Static storage duration [basic.stc.static]

All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program.

Community
  • 1
  • 1
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62
1

There is no dynamic memory allocation so there is no leak. What you have is a pointer pointing to a string literal which is stored somewhere in implementation defined read only memory.

Alok Save
  • 202,538
  • 53
  • 430
  • 533