0

Folks, here is an implementation of memset(), however I have been told that there is one logical mistake in the code. Could you help me find it.

I feel that a double pointer for the target string should be passed to this function, which will be like passing the address of the pointer variable and not the pointer itself.

I am getting an "access violation" when I execute the code in MS VC++ IDE.

The definition of the ā€˜Cā€™ Library function memset is

void *memset(char *s, char c, size_t n)

Copy c to the first n characters of s. Return s.
void *memset(char *s, char c, size_t n)
{
  size_t i;
  for (i = 0; i < n; i++, s++)
  {
    *s = c;
  }
  return s;
}
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by whyname
0

The definition of the ā€˜Cā€™ Library function memset is
void *memset(char *s, char c, size_t n)

Copy c to the first n characters of s. Return s.

The proper prototype is void * memset ( void * ptr, int value, size_t num );

void *memset(char *s, char c, size_t n)
{
size_t i;
for (i = 0; i < n; i++, s++)
{
*s = c;
}
return s;
}

Your own implementation should not be named the same that the standard function memset()

0

many thigns to be corrected here

1) protoype of the function should be void * memset( void * s, int c, size_t t)
2) s++ is not allowed since s is a void pointer, compiler would not knw the size of s to increment it -- so s is to be typecasted
3) function returns s which would be the pointing to the end of the memory block, the funciton should return a ptr pointing to the beginning of the memory block


correct implementation of memset

void * my_memset(void *s, int c, size_t n)
{
size_t i;
char * ptr = s;

for (i = 0; i < n; i++, ptr++)
{
*ptr = c;
}
return s;
}

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.