Regarding Null terminator

Hi All,

I am having a code something like this :

char *dest = NULL;
char *source = "abcdef";
int iLen =6;
dest = new char[iLen+1];
memcpy(dest, source, iLen+1);
dest[iLen]='\0';

Now my confusion is in the last line.should I use this line(i mean should I add the null termintor).
actually I use in both ways, by adding it, and by removing it, and tested in both the release and debug mode.
It is working fine.
but which approach would be better.......
is there anything specific with memcpy.

Thanks & Regs
[586 byte] By [developerid] at [2007-11-19 7:31:48]
# 1 Re: Regarding Null terminator
What in the world are you trying to accomplish?

In the case of the code you posted, adding the terminating '\0' is redundant, as you are already copying the 6 characters of your string as well as it's terminating '\0' (memcpy is copying 7 elements, iLen+1), and then you just write another 0 over dest[6].
rdrast at 2007-11-9 0:42:35 >
# 2 Re: Regarding Null terminator
This is a confusion.
as in the ode will memcpy, by itself include the terminating null character.....if i gave the len 1 byte more with the len of string, which I want to copy.
developerid at 2007-11-9 0:43:28 >
# 3 Re: Regarding Null terminator
Again, what exactly are you trying to accomplish?

When you declared your string literal (char *dest = "abcdef"), the compiler sees "abcdef" as a string, and adds a terminating '\0', so it is reserving space for the terminator, and putting it there.

If you had memcpy(dest, source, iLen), then indeed, you would need to manually place the terminating '\0', but you are copying iLen+1, which will include it.

I realize that is only a code fragment, but be warned, you can get into some serious trouble with memcpy, especially with strings.
rdrast at 2007-11-9 0:44:31 >
# 4 Re: Regarding Null terminator
Hi,
Thanks for your reply.Now with this, it is clear to me.
developerid at 2007-11-9 0:45:36 >
# 5 Re: Regarding Null terminator
Just out of curiosity...is there any need why you are using the old-style C constructs?
Andreas Masur at 2007-11-9 0:46:41 >
# 6 Re: Regarding Null terminator
Hi All,

I am having a code something like this :

char *dest = NULL;
char *source = "abcdef";
int iLen =6;
dest = new char[iLen+1];
memcpy(dest, source, iLen+1);
dest[iLen]='\0';

1) Do not use hard-coded results such as "iLen = 6". Use strlen() to get the length of the string.

2) Why not just use std::string? If it is a contiguous buffer of char, then use std::vector<char> and you don't have that call to "new" to deal with later on.

#include <string>
//...
std::string source = "abcdef";
std::string dest = source;

Using vector<char>

#include <vector>
//...
char *source = "abcdef";
std::vector<char> dest(source, source + strlen(source) + 1);

Regards,

Paul McKenzie
Paul McKenzie at 2007-11-9 0:47:40 >