tags:

views:

261

answers:

7

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;
}
+4  A: 

You shouldn't be changing the pointer that is returned.

Chris Thornhill
+4  A: 

Check the return value of the function. What does it return? What is it documented to return?

Greg Hewgill
+6  A: 

This has several problems.

void *memset(char *s, char c, size_t n)
{
  size_t i;
  for (i = 0; i < n; i++, s++)  /* incrementing s means you cannot return */
  {                             /* the original value */
    *s = c;                     /* consider using s[i] = c after not incr. s*/
  }
  return s;                     /* this should probably be a cast back to void */
}
ojblass
This returns the incorrect value - it should return a pointer to the original value of s.
Jonathan Leffler
+1  A: 

I have a feeling that your size_t n may be off by one.

Also s points at the end of the string instead of the original s by the end of the function.

Unknown
+1  A: 

You modify the value of s and then return it. This means you will be returning a pointer to the end of the memset region, not the start (which is probably what you want)

Nathan Reed
A: 

Hum... Try this:

void *memset (char* s, char c, size_t n){
  char* begin = s;
  char* end = begin + n;
  whilw (begin != end) *begin++ = c;
  return s;
}
Anzurio
+1  A: 

You make the statement that you are getting a "access violation". That indicates that you are calling the function with a non-null value for 's', however, either 's' was not properly initialized

// bad - s will have some arbitrary value as allocated on the stack (all bets are off)
char *s;
memset(s,0,100);

// good
char s[100];
memset(s,0,100);

// bad - the memset will generate an access violation on byte 101
char s[100];
memset(s,0,101);

// good
char *s = malloc(100);
memset(s,0,100);

** one note not related to the access violation... returning 's' the way you do is not the same behavior as the traditional memset() in string.h. In that library, the return value is supposed to be the value of 's' as input. In your code you are returning a pointer to the byte after the last byte which would generate an access violation. for example:

// good
char *s = malloc(100);
char *d = memset(s,0,100);
printf("%s\n",d);  // generates an access violation

in the memset() doc, d and s should have the same value. In your code, d = s[101];

Richard