TString::Data() output

ROOT Version: 6.18/00
Platform: ubuntu18.04.1
Compiler: gcc7.4.0


Hi! Can anybody explain the above output of the TString::Data() function? I’m confused, expect the char string to be “hello”.

Your “hello” string has been destroyed immediately after it has been used so, the “s” pointer is invalid (and you see garbage when you try to use it).

root [0] TString s("hello"); // remains in RAM
root [1] const char *p = s.Data(); // points to a valid address in RAM
root [2] p
(const char* 0x1f34db9)"hello"
1 Like

Thanks for a quick response. Interesting. I wonder why then following code works well?

root [0] Int_t length = TString("hello").Length();
root [1] length
(int) 5

Simply because the “length” does not depend on the “hello” string, which was deleted immediately after “length” was set.

1 Like

Nice, I understand now how it is. Data() sets pointer to the part of TString’s memory that is destroyed after expression is executed. Let me ask another question then. Why does following memory is not destroyed:

root [0] TNamed* n = new TNamed(TString("hello").Data(), "");
root [1] n->Print()
OBJ: TNamed	hello

I apologize for my incompetence here.

LearnCpp.com -> The stack and the heap
GeeksforGeeks.org -> Stack vs Heap Memory Allocation

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.