0

There are a few questions on here about how to use memset() in C or what a buffer is. But I have yet to find a good explanation for why it is necessary to use and what it actually does for your program.

I saw in this program that was trying to print out a rotating 3D cube that they used. I am struggling to see what this actually does for the program.

memset(buffer, backgroundASCIICode, width * height);

Would love any help trying to explain what a buffer is, and how memset() is used to create one.

  • 2
    Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Oct 04 '22 at 16:30
  • 1
    A buffer is basically some chunk of memory that is accessible by the application, so it lives somewhere on the stack or heap. The `memset` function basically sets some number of bytes to some value (often zero, but `backgroundASCIICode`) here. Typical use of a buffer is to allow for (temporary) storage of some value. Many C functions or library functions ask the user to provide a buffer, this is another way of knowing that the function is likely not going to allocate memory itself, it trusts the user to provide something it can use. – Cheatah Oct 04 '22 at 16:38
  • Does this answer your question? [What does it mean by buffer?](https://stackoverflow.com/questions/648309/what-does-it-mean-by-buffer) – Avi Berger Oct 04 '22 at 16:41

2 Answers2

1

memset is a C-standard function from string.h with the prototype:

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

It takes a pointer to a memory location, or buffer, in the form of void *s, a 1-byte value in the form of int c, and a number of bytes to be set in the form of size_t n.

The function writes the value in c into n-bytes starting at the memory address s

For instance the code snippet:

int *array = malloc(sizeof(int) * 10);
memset(array, 0, 10 * sizeof(int));

...allocates a buffer large enough for 10 ints, and then writes zeroes in every byte in that buffer.

In the example you give, backgroundASCIICode is being copied into width * height bytes beginning at the pointer buffer.

Generally speaking a buffer is any memory region that you have access to via a pointer to the first byte, which is why memset takes a pointer to the buffer via a void*, since it doesn't care what kind of data is stored there, since it's just going to overwrite each byte.

Willis Hershey
  • 1,520
  • 4
  • 22
1

The memset function is used to set all bytes in a particular block of memory to a given value.

Here, a "buffer" is just some arbitrary block of memory, i.e. a single variable, array, struct, or any combination thereof. memset doesn't create a buffer, but rather modifies the values in it.

In this particular case, buffer is the start of some piece of memory already in use, whose size in bytes is at least width * height, and all of those bytes are set to the value of backgroundASCIICode.

dbush
  • 205,898
  • 23
  • 218
  • 273