2

The man page of memset function in C, says

The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.

And the signature of memset is as below:

void *memset(void *s, int c, size_t n);

Since the function fills the first n bytes of the memory, why the c's type is int and not char? Couldn't it be char and works just fine? What will happen if we set c a number greater than size of a byte?

I tried to play with memset to get more into it but it didn't help me.

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

int
main(int argc, char *argv[]) {

        char* s[5] = {0, 0, 0, 0, 0};
        memset((void*)s, 257, 5);
        for (int i=0; i<5; i++)
                fprintf(stdout, " %d", s[i]);
        putc('\n', stdout);
        return 0;
}

The output is:

[amirreza@localhost memst]$ gcc memst.c 
[amirreza@localhost memst]$ ./a.out 
 16843009 0 0 0 0
Amir reza Riahi
  • 1,540
  • 2
  • 8
  • 34
  • 1
    Do not use “integer” (as a noun) to mean a type. The types `char`, `unsigned char`, `short`, `long`, and others are all integer types (as an adjective). The type of the second argument is `int`, not “integer”. – Eric Postpischil Apr 11 '23 at 19:23
  • @EricPostpischil thanks for noting it. I edited the post. – Amir reza Riahi Apr 11 '23 at 19:26
  • 2
    Hardly any (any at all?) C functions either take a `char` argument, or `return` a `char` as the function value. They typically use `int`, and note that the constant value `'A'` is type `int`. Please don't confuse "character" with `char`. – Weather Vane Apr 11 '23 at 19:27
  • @WeatherVane Why it's typical to use `int` when `char` is enough? – Amir reza Riahi Apr 11 '23 at 19:36
  • Because `int` is the "natural" type. We don't generally use the smallest of anything that we need unless there are severe restrictions on memory. As for function `return` values, it allows for error status to be returned, for example `int fgetc(FILE *stream);` can `return EOF;`. – Weather Vane Apr 11 '23 at 19:39
  • ...and because of "alignment". If a `char` function argument will take 32 bits on the stack, then they might as well be used. And, processors usually work more efficiently with the natural register size. – Weather Vane Apr 11 '23 at 19:46
  • 2
    @WeatherVane At the ABI level, yes, probably `char` arguments will be sign- or zero-extended to register width (whichever is easier for the CPU) but this is _not_ why hardly any C library functions take `char` arguments. The actual reason, as stated in the linked question's accepted answer, is backward compatibility with un-prototyped function declarations. – zwol Apr 11 '23 at 20:05

0 Answers0