Proper function declaration to avoid a memory leak
-
I have a function which returns a char* and I am trying to avoid a memory leak. So far it is in this format: char* MyFunction(char *szBuffer) { char *szTmpBuffer = new char[strlen(szBuffer) + 1]; ...function body... return szTmpBuffer; } And it is called somewhat like this: char *szBuffer = MyFunction(szString); but if after I use szBuffer I try to delete it: delete [] szBuffer; I get a Debug Assertion failed...so the question is, what is the proper way to call new within a function then delete the pointer outside of the function w/o causing errors and avoiding memory leaks?
-
I have a function which returns a char* and I am trying to avoid a memory leak. So far it is in this format: char* MyFunction(char *szBuffer) { char *szTmpBuffer = new char[strlen(szBuffer) + 1]; ...function body... return szTmpBuffer; } And it is called somewhat like this: char *szBuffer = MyFunction(szString); but if after I use szBuffer I try to delete it: delete [] szBuffer; I get a Debug Assertion failed...so the question is, what is the proper way to call new within a function then delete the pointer outside of the function w/o causing errors and avoiding memory leaks?
You code is fine. I tried it and no assertion was fired. What line/file does the assertion message indicate?
"Opinions are neither right nor wrong. I cannot change your opinion of me. I can, however, change what influences your opinion." - David Crow
-
I have a function which returns a char* and I am trying to avoid a memory leak. So far it is in this format: char* MyFunction(char *szBuffer) { char *szTmpBuffer = new char[strlen(szBuffer) + 1]; ...function body... return szTmpBuffer; } And it is called somewhat like this: char *szBuffer = MyFunction(szString); but if after I use szBuffer I try to delete it: delete [] szBuffer; I get a Debug Assertion failed...so the question is, what is the proper way to call new within a function then delete the pointer outside of the function w/o causing errors and avoiding memory leaks?
-
Exactly: DAMAGE: after normal block (#3604) at (memory address)
-
Yep, I was overwriting...thanks for pointing out my stupid mistakes ;P