Search code examples
c++dynamic-memory-allocationmemset

Why does memset fail in this case?


#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        int *b1 = (int *)malloc(sizeof(int)*4);
        memset(b1, 0, sizeof(b1));
        cout<<"\nArray after memset:";
        for(int i=0; i<4; i++)
             printf("\t%d", b1[i]);
        for(int i=0; i<4; i++)
             scanf("%d", &b1[i]);
        free(b1);
    }
}

Input: 2 10 20 30 40 10 20 30 40

For the given input, the code gives the following output:

Array after memset: 0 0 0 0

Array after memset: 0 0 30 40

Why does memset fail in the second case?

(Also, I noticed that on removing the free(b1) statement, memset works fine).


Solution

  • sizeof(b1) will return the size of b1 and variable storing an integer pointer.

    You want the size of the thing that it is pointing to - i.e. the parameter of malloc - sizeof(int)*4

    Use that instead in memset

    Also why are you using scanf, malloc in C++ code. Why not use std::vector?