struct pointer casting及其内存分配

时间:2012-05-31 11:48:39

标签: c

这里的重点是代码int header = (((int)(txUserPtr) - 4)) UserTypes和struct pointer casting的插图很有帮助!我应该如何设置传入指针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 */ 
}

3 个答案:

答案 0 :(得分: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 */ 
}

答案 1 :(得分:0)

很难理解这个问题。

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

我认为,为了解决这个问题,有必要提供有关平台精确内存映射的更多信息。

答案 2 :(得分:0)

这段代码怎么样?

void Fun (int header, UserTypes* txUserPtr)
{
  // exactly safe code
  if ( header & 0xFF000000u) != 0xAA000000u ) {
    error("sth error\n");
  }
  /*the following is the rest */ 
}