gpt4 book ai didi

c++ - 为什么结构数组的 memset 会改变程序行为?

转载 作者:太空宇宙 更新时间:2023-11-04 05:52:19 24 4
gpt4 key购买 nike

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

实际开工:

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

预期成绩:

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

请告诉我如何解决这个问题?

最佳答案

你在那里用完了边界,它调用了 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));

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

关于c++ - 为什么结构数组的 memset 会改变程序行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37341430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com