c++ - Possible Memory Leak: new char[strlen()] -


this basic question , pretty sure know answer, seeing consequence being wrong segfault figure should ask. have been using strlen() , new char[] operator in following way quite time , noticed threw red flag:

void genericcopy(char *somestring, char *someotherstring) { someotherstring = new char[strlen(somestring)]; strcpy(someotherstring,somestring); } 

my question is, seeing string should null terminated, should doing such:

void genericcopy(char *somestring, char *someotherstring) { someotherstring = new char[strlen(somestring)+1]; strcpy(someotherstring,somestring); someotherstring[strlen(someotherstring)] = '\0'; } 

so far have never had problem first method, doesn't mean i'm doing right. since length being return strlen()is number of characters in string without null terminator new isn't reserving space '/0'... @ least don't think is.

first of all, should know function of yours pointless write, use strdup (if available on system).

but yes, need additional byte store \0, new char[strlen(somestring)+1];. however, there no need manually add \0; strcpy this.

you should use valgrind discover , similar bugs in code.

there additional problem in code; code leak someotherstring; not returned called from. either need change method like:

char *genericcopy(char *something) { char *copy = new char[strlen(somestring)+1]; strcpy(copy,somestring); return copy; } 

and copy follows:

copy = genericcopy(something); 

or need change method like:

void genericcopy(char *something, char **copy) { *copy = new char[strlen(somestring)+1]; strcpy(*copy,somestring); } 

and call as:

genericcopy(something, &copy); 

if you'll using c++ change method prototype to:

void genericcopy(char* somestring, char*& someotherstring) 

and call as:

genericcopy(something, copy); 

then someotherstring passed reference, , new value allocate propagate outside of method.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -