I encountered the following example of using memset in tutorialspoint:
#include <stdio.h>
#include <string.h>
int main(){
char src[40];
char dest[100];
memset(dest, '\0', sizeof(dest));
strcpy(src, "This is tutorialspoint.com");
strcpy(dest, src);
printf("Final copied string : %s\n", dest);
return(0);
}
I don't get why the memset line is used, as the compile and result are the same when that line is commented. I would like to ask is that line necessary? or is it a good practice to do so when doing strcpy()? or it is just one random line.
Thanks!
It's not needed in this case, in the sense that it has no effect on the output. It might be needed in some similar cases.
char dest[100];
This defines dest
as a local array of 100 char
s. Its initial value is garbage. It could have been written as:
char dest[100] = "";
or
char dest[100] = { 0 };
but none of those are necessary because dest
is assigned a value before it's used.
strcpy(src, "This is tutorialspoint.com");
strcpy(dest, src);
This copies the string contained in src
into the array dest
. It copies the 26 characters of "This is tutorialspoint.com"
plus 1 additional character, the terminating '\0;
that marks the end of the string. The previous contents of the dest
array are ignored. (If we were using strcat()
, it would matter, because strcat()
has to find a '\0'
in the destination before it can start copying.)
Without the memset()
call, the remaining 73 bytes of dest
would be garbage -- but that wouldn't matter, because we never look at anything past the '\0'
at dest[26]
.
If, for some reason, we decided to add something like:
printf("dest[99] = '%c'\n", dest[99]);
to the program, then the memset()
would matter. But since the purpose of dest
is to hold a string (which is by definition terminated by a '\0'
null character), that wouldn't be a sensible thing to do. Perfectly legal, but not sensible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With