Zeroing out a string
suggest changeYou can call memset to zero a string or any other memory block. str is the block to zero, and n is the number of bytes. n must stay inside that object.
#include <stdlib.h> /* For EXIT_SUCCESS */
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[42] = "fortytwo";
size_t n = sizeof str; /* Take the size not the length. */
printf("'%s'\n", str);
memset(str, '\0', n);
printf("'%s'\n", str);
return EXIT_SUCCESS;
}
Prints:
'fortytwo'
''
Another example:
#include <stdlib.h> /* For EXIT_SUCCESS */
#include <stdio.h>
#include <string.h>
#define FORTY_STR "forty"
#define TWO_STR "two"
int main(void)
{
char str[42] = FORTY_STR TWO_STR;
size_t n = sizeof str; /* Take the size not the length. */
char *point_to_two = strstr(str, TWO_STR);
printf("'%s'\n", str);
/* Remaining bytes only. Using n here would write past the array. */
if (point_to_two != NULL) {
memset(point_to_two, '\0', n - (size_t)(point_to_two - str));
}
printf("'%s'\n", str);
memset(str, '\0', n);
printf("'%s'\n", str);
return EXIT_SUCCESS;
}
Prints:
'fortytwo'
'forty'
''
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents