Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behaviour of memset()

Tags:

c++

cstring

I am initializing array with 99 in all the elememts

#include<iostream>
#include<cstring>
int main(){
    int a[10];
    memset(a,99,10);
    std::cout<<a[0]<<std::endl;
    return 0;
}

but the output I am getting is unexpected.

Output:-

1667457891

What is the reason behind the abnormal behavior of this memset function.

like image 573
dead programmer Avatar asked Oct 27 '12 17:10

dead programmer


1 Answers

Firstly, memset takes the size in bytes, not number of elements of the array, because it cannot know how big each element is. You need to use sizeof to get the size in bytes of the array and give that to memset instead:

memset(a, 99, sizeof(a));

However, in C++, prefer std::fill because it is type-safe, more flexible, and can sometimes be more efficient:

std::fill(begin(a), end(a), 99);

The second and more pressing problem is that memset and fill have different behaviour in this instance, so you must decide which you want: the memset will set each byte to 99, whereas fill will set each element (each int in your case) to 99. If you want an array full of integers that equal 99, use fill as I showed it. If you want each byte set to 99, I would recommend casting the int* to a char* and using fill on that instead of memset, but memset will work for that too.

like image 197
Seth Carnegie Avatar answered Oct 05 '22 17:10

Seth Carnegie