Chapter Contents

Previous

Next
memset

memset



Fill a Block of Memory with a Single Character

Portability: ISO/ANSI C conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
CAUTION
IMPLEMENTATION
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <string.h>

void *memset(void *to, int ch, size_t n);


DESCRIPTION

memset fills a block of memory (indicated by to ) with the specified character ( ch ). The size of the area to be filled is n .


RETURN VALUE

memset returns a pointer to the to area.


CAUTION

The third argument to memset is size_t . If a negative number is passed, massive overlaying of memory occurs.


IMPLEMENTATION

The compiler generates inline code for memset unless memset is undefined (by an #undef statement) to prevent this. The inline code can still call a library routine in special cases (for example, if the length is a variable whose value is larger than 16 megabytes).

The code generated for memset usually uses the MVCL instruction to propagate characters through memory. If more than 16 megabytes of memory are to be filled, the library routine is called, which processes 16M-1 bytes at a time. For more information on optimizing your use of memcpy , see Optimizing Your Use of memcmp, memcpy, and memset.


EXAMPLE

#include <string.h>
#include <stdio.h>

main()
{
   char padded_str[65], *unpadded_str, input[66];
   int ln;

   puts("Enter a string no longer than 64 characters.");
   unpadded_str = gets(input);

      /* Copy unpadded_str to padded_str, padding with stars. */
   ln = strlen(unpadded_str);
   if (ln <= 64) {
      memcpy(padded_str, unpadded_str, ln);
      memset(padded_str +ln, '*', 64 - ln);
   }
   padded_str[64] = '\0';
   printf("The unpadded string is:\n %s\n", unpadded_str);
   printf("The padded string is :\n %s\n", padded_str);
}


RELATED FUNCTIONS

memfil


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.