The necessity to memset with '\\0', in a t

2019-05-11 16:57发布

问题:

I encountered the following example of using memset in tutorialspoint: (I am not familiar with C.)

#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!

回答1:

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 chars. 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.



回答2:

the posted code could skip the initialization via memset().

A time it really becomes useful is when debugging and you use the debugger to display the contents of the variable.

Another time to use memset() is when allocating something like an array of pointers, which might not all be set to point to something specific, like more allocated memory.

Then when passing those pointers to 'free()the unused pointers are set to NULL, so will not cause a crash when passed tofree()`



标签: c memset