0

这里的重点是int header = (((int)(txUserPtr) - 4))UserTypes和struct指针强制转换的代码说明很有帮助!我应该如何设置传入指针txUserPtr,以便Fun()跳过以下行。我不想执行error()

typedef union UserTypes
{
    SAUser           AUser;
    BUser            BUser;
    SCUser           CUser;
    SDUser           DUser;
} UserTypes;

typedef struct AUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } AUser;
typedef struct AUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } AUser;

typedef struct BUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } BUser;

typedef struct CUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } CUser;

typedef struct DUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } DUser;

//this is the function I want to test

void Fun(UserTypes * txUserPtr)
{

   int header = (*((int*)(txUserPtr) - 4));

   //the problem is here
   //how should i set incoming pointer "txUserPtr" so that 
   //Fun() would skip following lines.
   // I don't want to execute error()

        if((header & 0xFF000000) != (int)0xAA000000)
        {
            error("sth error\n");
        }
   /*the following is the rest */ 
}
4

3 回答 3

1

代码依赖于未定义的行为,以及各种实现定义的行为。在您的代码中的某处应该有一个看起来类似于

typedef struct 
{
  unsigned int header;
  UserTypes user;
} AHeaderPlusUserTypes;

找到该结构后,修复代码:

void Fun (AHeaderPlusUserTypes* txUserPtr)
{
  if((txUserPtr->header & 0xFF000000u) != 0xAA000000u)
  {
    error("sth error\n");
  }
  /*the following is the rest */ 
}
于 2012-05-31T13:36:54.203 回答
0

这段代码怎么样?

void Fun (int header, UserTypes* txUserPtr)
{
  // exactly safe code
  if ( header & 0xFF000000u) != 0xAA000000u ) {
    error("sth error\n");
  }
  /*the following is the rest */ 
}
于 2012-05-31T13:47:22.853 回答
0

很难理解这个问题。

您希望避免指针在其最重要的位中具有某种位模式,但尚不清楚指针是否仍期望以某种方式包含您可以在已删除代码中访问的某些内容的地址。

我认为,为了解决这个问题,需要更多关于您平台的确切内存映射的信息。

于 2012-05-31T11:53:28.553 回答