开发者

when does the memory, pointed by (char *) as function parameter gets deleted?

code 1 :

void foo(char * text) {}

foo("Test");

as far as i understand, this will happen :

  • memory is allocated for "Test"

  • pointer is created and its value is copyed to (char * text pointer), so (char * text) points to the place in memory, where "Test" is (better to say开发者_StackOverflow中文版, on the first char of "Test")

  • after the function is done, it destroys the pointer(char * text), pointing to the beginning of "Test", doesnt create this a memory leak?

  • and the question is, when does the "Test" gets deleted, when the function destroys only the pointer

isn't it better to do smth. like that? :

char * _text = "Test";
foo(_text);
delete[] _text;


You can think of string literals as being part of the code. They aren't dynamically allocated, they have so-called "static storage duration", which means they exist for the duration of the program, and they don't need to be freed (indeed, must not be freed).

It is always wrong to delete[] something that wasn't created with new[], so your second code snippet has undefined behavior.


"Test" is a string literal, which has a static storage duration. It will not be deleted until the program works. And you should not delete it by yourself.


Actually it doesn't get deleted.

That string is allocated in data segment and the call to foo("Test") just pushes on the stack the pointer to that string, without "copying" it as you are saying.

It is not leaked memory because the string is part of the final binary file and it will always be there, in a section of the binary that is just for that kind of things (constants and so on).

It happens that the string itself (the bytes for "Test") are placed in data segment in a read-only section while the pointer (eg char *_test = "Test") is instead stored in a read-write section (stack or heap, it depends how the pointer is initialized and used). You are allowed to modify the pointer but that won't delete the string from the data segment.


Hard coded values in C are actually compiled into the binary and as such are not allocated. More correctly they appear in the "data" section of the executable and live as long as the program does.

Also, pointers are not "destroyed". Remember that pointers are just addresses to memory that may be anywhere (stack/heap) but pointers a not objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜