user9848444
user9848444

Reputation:

How memset() works in c++

I created a boolean 2D array and used memset like this :

bool chk[3][3];

memset(chk, 1, 9*sizeof(chk[0]));

I got output as expected using the following blocks of code (got 1 in every row )

for(int i = 0 ; i < 3; i++){
    for(int j = 0; j < 3; j++)
        cout<<chk[i][j] <<" ";
    cout<<endl;
}

but when I tried to manipulate the array I got unexpected result

and then I tried with

memset(chk, 1, 9*sizeof(chk[0][0]));

and this time everything was fine and got my expected result(after manipulation)

Can you please help me pointing out what exactly happened in memset() ?

Upvotes: 2

Views: 1080

Answers (4)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145439

The memset call in your first code snippet has three problems:

  1. The size calculation is incorrect. Instead of 9*sizeof(chk[0]) you could use 3*sizeof(chk[0]). But really you should just use sizeof(chk), because you have a local variable, not a pointer, as you would have with a formal argument.

  2. The assumption that memory representation of true is bitpattern 1, is not guaranteed by the standard. In practice it will hold, but it would be far better to use the value true directly instead of a needless assumption.

  3. In C++ simply zero-initialize the variable to make it all zeroes, e.g. bool chk[3][3] = {};, or use std::fill to fill an array with a given value, e.g. fill( &chk[0][0], &chk[0][0] + 9, true );.


Addendum: to be pedantic, in point 1 there is an assumption that a bool is 1 byte. That's also an assumption that holds in practice but is not guaranteed by the standard. Happily it's not an issue for use of std::fill.

Upvotes: 5

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14688

sizeof(array) obviously would return size of array in bytes. In first case the array you submitted to the operator is one of sub-arrays. Multidimensional arrays in C++ aren't. They are single-dimensional arrays of arrays. Do sizeof(chk) to evaluate size of full array and divide it by sizeof(chk[0][0]) to get amount of elements. Don't use memset because if would do some strange thing to binary representation of bool, use std::fill.

Upvotes: 0

eerorika
eerorika

Reputation: 238461

Let's take a look at what the documentation of std::memset says:

If count is greater than the size of the object pointed to by dest, the behavior is undefined.

In the first code, 9*sizeof(chk[0]) is greater than the size of chk, and therefore the behaviour of the program is undefined.

memset(chk, 1, sizeof chk) would be simpler, and obviously correct as far as the size is concerned.

Upvotes: 1

Swordfish
Swordfish

Reputation: 13144

sizeof(chk[0]) is sizeof(bool[3]) which is obviously different from sizeof(chk[0][0]) which is sizeof(bool).

With memset(chk, 1, 9*sizeof(chk[0])); you write beyond the bounds of the array chk and get undefined behaviour.

Upvotes: 2

Related Questions