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

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.