The reason functions often return a value is to return an error state to the calling function. In memory related functions it's usually the same pointer as where your result should be (including NULL). In your example you might not want to use the return value of your my_memset
function, but usually it's because it can be included in a code evaluation (can't think of a better word for this), e.g.
if(!my_memset((void *)str, 'a', 5))
{
printf("An error occurred in my_memset()\n");
}
or in a macro, e.g. to return pointer to the end of the memory where you copied your char
:
#define INIT_MEM_PTR_END(a,x) (my_memset((void *)&(a), (x), sizeof(a)) + sizeof(a))
This is probably not a great example (plus the potential issues if a
is already a pointer, etc...), but it shows that you can reuse the result without having to write another couple of lines for this to evaluate the result and so on.
You should also check your pointers before dereferencing them. If for example void *b
is NULL, you'll have a segmentation fault.
Nothing wrong with passing in void *
, other than the fact that the intention of the function may not be as clear as when passing pointer to a particular data type. Make sure you cast it to something valid though inside. Also this way, the function can be used to set any memory to a particular hex value (through char) or all 0's quite easily.
It would seem like in this case b
should be cast to the same type as the value you're trying to copy into it, an int
; however, then the len
argument becomes unclear, is it size in bytes or number of times c
should be copied to the b
pointer?
Since in your main()
you're copying a char
into that memory location, then it's just better to change your c
to a char
, cast your b
to a char*
and make len
the length in bytes or number of times c
should be copied to *b
. Avoid ambiguity.
The way you have written it, it will copy c
number of times specified by len
or until you meet the null character, whichever is shortest/soonest. That's fine, if that's your intention.
void *my_memset(void *b, char c, int len)
{
char *b_char = (char *)b;
if (b == NULL) return NULL;
while(*b_char && len > 0)
{
*b_char = c;
b_char++;
len--;
}
return b; //as this pointer has not changed
}
int main()
{
char *str;
str = strdup("hello");
if (!my_memset((void *)str, 'a', 5))
{
printf("An error occurred in my_memset()\n");
}
else
{
printf("%s\n", str);
}
}