What's new

Manipulating strings in C

smcd

Active member
memory leak

char *test = new char[20];
test = "hello";

The above causes a memory leak. Hard to explain it here but when you use 'new' to allocate your memory, the pointer gets assigned the address to the starting element. If you later go and change what the pointer points to, 'test = "hello"' then the program no longer has access to the previously allocated memory because the address (held in 'test') was overwritten to point to a hardcoded constant string. :ermm:
 

Doomulation

?????????????????????????
Well yes, THAT will cause a memory leak. I can see that as well.
But I don't do that, I assign the string directly to the pointer, such as:

char* bah = "hello";
 

Top