From: David D. H. <wow...@sk...> - 2001-09-03 23:22:21
|
> I'm still in doubt wether : > memset (&str, 0, strlen(str)); > should change to : > memset(&str, 0, sizeof(str)); Actually, both of these are problematic. The best way would be: memset(str,0,strlen(str)); First, using &str is a bad idea. If str is of type char [] (in other words a normal string), then the & is redundant - char [] transparently coverts to char * in C and C++. If str is of type char *, then trouble arises: char *foo = strdup("hi there"); memset(&foo,0,strlen(foo)); Will NOT set the memory allocated by the strdup to nulls, it will set the POINTER foo to null, and anything else in the area! Second, the issue of sizeof() vs. strlen() - same problem. If str is of type char [<x>}, where <x> is known at compile time, then sizeof(str) will be the length of the buffer. However, is str is of type char [] (in other words, the length is not known at compile time), the sizeof(str) will fail. Consider: File1.c: char foo[] = "Hello, baby!"; File2.c: extern char foo[]; memset(foo,0,sizeof(foo)); This won't work, since the size of foo isn't know in file2.c. Also, if foo is of type char *, then sizeof(foo) == sizeof(char *), not the size of the string pointed to. It's better by far to use strlen explicitly. memset(foo,0,strlen(foo)) will always work, whether foo is char [], char *, or ClassWhichCanConvertToCharStar. |