problem with heap allocation

Hi,
I was implementing functions which work on C style string . I wrote strdup(const char*) which is supposed to copy the given string and copy it in a new string and finally return a pointer to that new string. Code is:

char* strdup(const char* str)
{
int n = length(str);
char* new_str = new char[n];
for (int i = 0; i < n; i++) new_str[i] = str[i];
return new_str;
}

my problem is that the new string which is created has a length more than the n . to calculate length i used :

int length(const char* str)
{
int n = 0;
while (str[n]) n++;
return n;
}
when i wrote code to test these function i got HelloWorld!ýýýýÝñDÝÝ(i think these nonsene symbols mean sth is wrong with mem allocation)
char* str = c_str::strdup("HelloWorld!"); // For testing
The problem is in your strdup, you don;t allow for the null terminator. Your new_str has no null terminator.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Topic archived. No new replies allowed.