0
#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 ?

2
  • 4
    2*sizeof(res)...hmmm.. Commented May 20, 2016 at 8:16
  • Thanks . Today I lost my common sense it seems .. But I don't know why you guys down vote . Commented May 20, 2016 at 8:40

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

multiplied version is not a good idea. We have to maintain it if the dimension of res changed.
@songyuanyao That is why that's a second choice, but nevertheless, it's possible.
1
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));

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.