In C programming the <string.h> memset function set the memory block to some values.The declaration of the function is given below.
|void *memset(void *s, int c, size_t n);|
s -The pointer to memory which is to be set with some value.
c -This value is converted to ‘unsigned char’ and copied to the memory block pointed by ‘s’.
n -The number of memory blocks to be set with the ‘c’ value.
void* -Returns the value of ‘s’.
This function is useful if you are allocating a dynamic memory and wants to set the memory with some value to prevent getting from unexpected result.
Link :C stdlib.h malloc
int c = ‘c’ , sz=10;
s = (char*)malloc(sz);
ret = (char*)memset(s , c , sz);
s[sz-1] = ‘\0’ ; //without this line some garbage value is attached after the 10th character
free(s); //frees the dynamic memory allocated by malloc
If compile without the line ‘s[sz-1]=’\0’ in VS I get output as,
the value “²²²²” is a garbage value.And I got this since the memory block has no null terminating character there is no way to signal the compiler the end of string or block has reached,so the compiler simply outputs some garbage value present in the memory after the allocated memory block.
Link :C stdlib.h free
P.S. Do not not forget to include null-terminating character when ‘memset’ is used.