C programming memset string.h


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);

Parameters:
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.

Return type
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
Code example

char *s , *ret ;

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

printf(“s=%s”, s);
printf(“\nret=%s”, ret);

free(s); //frees the dynamic memory allocated by malloc

Output,

s=ccccccccc
ret=ccccccccc

If compile without the line ‘s[sz-1]=’\0’ in VS I get output as,

s=cccccccccc²²²²
ret=cccccccccc²²²²

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.


Related links

->C strcpy string.h

->C memcpy string.h

->C strlen string.h

->C strerror string.h