Reputation: 355
#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:
- pipeName : myPipeName , PIPE :myPipeName
- pipeName : , PIPE : myPipeName
Expected o/p:
- pipeName : myPipeName , PIPE :myPipeName
- pipeName : myPipeName , PIPE :myPipeName
Please let me know how can I solve this ?
Upvotes: 0
Views: 187
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
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
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