Skip to main content

SA0065:添加到基本大小的指针不正确

检测要添加的值与指针的基本大小不匹配的指针添加。只能添加基本数据大小及其倍数的文字而不会出现错误。

理由:在 CODESYS (与 C 和 C++ 相反),当添加具有整数值的指针时,仅将该整数值添加为字节数,而不是整数值乘以基本大小。

76. ST 中的示例
pINT := ADR(array_of_int[0]);
pINT := pINT + 2;   //in CODESYS, pINT then points to array_of_int[1]

此代码在 C 中的功能会有所不同:

short* pShort
pShort = &(array_of_short[0])
pShort = pShort + 2;  //in C, pShort then points to array_of_short[2]


因此,在 CODESYS,您应该始终将指针基本大小的倍数添加到指针中。否则,指针可能指向 未对齐 内存(取决于处理器)在访问它时可能会导致对齐异常。

重要性:高

77. 例子
VAR
    pudiTest:POINTER TO UDINT;
    udiTest:UDINT;
    prTest:POINTER TO REAL;
    rTest:REAL;
END_VAR
pudiTest := ADR(udiTest) + 4;    // OK
pudiTest := ADR(udiTest) + ( 2 + 2 );    // OK
pudiTest := ADR(udiTest) + SIZEOF(UDINT);    // OK
pudiTest := ADR(udiTest) + 3;    // SA0065
pudiTest := ADR(udiTest) + 2*SIZEOF(UDINT);    // OK
pudiTest := ADR(udiTest) + ( 3 + 2 );    // SA0065
prTest := ADR(rTest);
prTest := prTest + 4;    // OK
prTest := prTest + ( 2 + 2 );    // OK
prTest := prTest + SIZEOF(REAL);    // OK
prTest := prTest + 1;    // SA0065
prTest := prTest + 2;    // SA0065
prTest := prTest + 3;    // SA0065
prTest := prTest + ( SIZEOF(REAL) - 1 );    // SA0065
prTest := prTest + ( 1 + 4 );    // SA0065

输出在 留言 看法:

  • sa_icon_message.png SA0065:基本大小的指针添加不正确