Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is memset() incorrectly initializing int?

Tags:

c++

c

memset

Why is the output of the following program 84215045?

int grid[110]; int main() {     memset(grid, 5, 100 * sizeof(int));     printf("%d", grid[0]);     return 0; } 
like image 339
Ahmad Avatar asked Aug 17 '11 22:08

Ahmad


People also ask

Why does memset take an int?

memset predates (by quite a bit) the addition of function prototypes to C. Without a prototype, you can't pass a char to a function -- when/if you try, it'll be promoted to int when you pass it, and what the function receives is an int .

Why does memset only work 0 and 1?

memset allows you to fill individual bytes as memory and you are trying to set integer values (maybe 4 or more bytes.) Your approach will only work on the number 0 and -1 as these are both represented in binary as 00000000 or 11111111 . Show activity on this post. Because memset works on byte and set every byte to 1.

Does memset work in C?

The memset() function sets the first count bytes of dest to the value c. The value of c is converted to an unsigned character.

Is memset faster than fill?

memset can be faster since it is written in assembler, whereas std::fill is a template function which simply does a loop internally.


1 Answers

memset sets each byte of the destination buffer to the specified value. On your system, an int is four bytes, each of which is 5 after the call to memset. Thus, grid[0] has the value 0x05050505 (hexadecimal), which is 84215045 in decimal.

Some platforms provide alternative APIs to memset that write wider patterns to the destination buffer; for example, on OS X or iOS, you could use:

int pattern = 5; memset_pattern4(grid, &pattern, sizeof grid); 

to get the behavior that you seem to expect. What platform are you targeting?

In C++, you should just use std::fill_n:

std::fill_n(grid, 100, 5); 
like image 110
Stephen Canon Avatar answered Oct 04 '22 11:10

Stephen Canon