为什么memset的结构数组改变了程序的行为?

时间:2016-05-20 08:15:17

标签: c++ c arrays sizeof memset

#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;
}

实际o / p:

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

预期o / p:

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

请让我知道如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

你在那里跑出界限,调用undefined behavior

更改

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

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

或者,如果您更喜欢相乘的版本(为了更好的可读性,可能?),请使用

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

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

也就是说,未初始化的自动变量值是不确定的。 不要尝试使用它们。

答案 1 :(得分: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

写出数组绑定是未定义的行为,因此请更改为:

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

答案 2 :(得分:0)

您正在设置错误的尺寸值

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

应该是

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

由于sizeof(res)以字节为单位返回数组的大小。

或者

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

由于sizeof(Response)以字节为单位返回Response typedef结构的大小。