Bhavith C Acharya
Bhavith C Acharya

Reputation: 355

Why memset of array of structure changing the program behaviour?

#include <stdio.h>
#include <string.h>
#define PIPE "myPipeName"

typedef enum 
{
    ID1,
    ID2
}TEST_ID;

typedef struct
{
    double dCnt;
    TEST_ID id ;
}Response;

int main()
{
    char pipeName[256]=PIPE;
    Response res[2];
    printf("1. pipeName : %s , PIPE : %s\n",pipeName,PIPE);
    memset(res,0,2*sizeof(res));
    printf("2. pipeName : %s , PIPE : %s\n",pipeName,PIPE);

    return 0;
}

Actual o/p:

  1. pipeName : myPipeName , PIPE :myPipeName
  2. pipeName : , PIPE : myPipeName

Expected o/p:

  1. pipeName : myPipeName , PIPE :myPipeName
  2. pipeName : myPipeName , PIPE :myPipeName

Please let me know how can I solve this ?

Upvotes: 0

Views: 187

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

You're running out of bound there, which invokes undefined behavior

Change

 memset(res,0,2*sizeof(res));
              ^^^^^^^^^^^^

to

memset(res,0,sizeof(res));

or, if you prefer the multiplied version (for better readability, maybe?), use

memset( res , 0 , 2 * sizeof(res[0]));

or

memset( res , 0 , 2 * sizeof(Response));

That said, uninitialized automatic variable value is indeterministic. Don't try to use them.

Upvotes: 4

Biruk Abebe
Biruk Abebe

Reputation: 2233

Response res[2];//is an array of 2 Responses

sizeof(res);//get the size of the array in bytes

memset(res,0,2*sizeof(res));//the multiplication by the size of the array is not needed here and 
                            //the memset is writing 0 out of bound of the array and probably
                            //into pipeName which would be treated as null terminator character

Writing out of the array bound is undefined behavior, so change to:

memset(res,0,sizeof(res));

Upvotes: 1

LPs
LPs

Reputation: 16243

You are setting a wrong size value

memset(res,0,2*sizeof(res));

Should be

memset(res,0,sizeof(res));

Because of sizeof(res) return the size of array in bytes.

Or

memset(res,0,2*sizeof(Response));

Because of sizeof(Response) return the size of the Response typedef struct in bytes.

Upvotes: 0

Related Questions