Wednesday, November 30, 2011

memset

1) What is the output of this program?

#include <stdio.h>

int main () {

   char string[10];
   char *p;
   int i=0;
 
   strcpy(string, "HELLOWORLD");

   printf("\nBefore memset: ");
   for (i=0; i<10;i++) {
      printf("%c", string[i]);
   }

   p = string;
   memset(p, '\0', sizeof(p));
 
   printf("\nAfter memset: ");

   for (i=0;i<10;i++)  {
      printf("%c", string[i]);
   }

   printf("\n");
}


2) The second question is: In the above program what would be the output if the memset was changed to
memset(p, '\0', sizeof(*p));
?






Answers Below:

1) 
Before memset: HELLOWORLD
After memset: LD


2)
Before memset: HELLOWORLD
After memset: ELLOWORLD


Be careful when using memset with pointers. In the above example, in order to zero out all the contents of "string", the memset statement should have been as follows

memset(p, '\0', sizeof(string));

To read more about memset check here and here

No comments:

Post a Comment