0

我的代码非常适合从链表的值填充数组而无需优化。一旦我启用优化 (-02) 数组中的第一个值正确加载,但所有后续值显示不正确(无效的内存范围)。

typedef struct lineInfo_s lineInfo_t;

struct lineInfo_s{
    unsigned short * lineBuffer;
    volatile lineInfo_t * next;
    volatile lineInfo_t * prev;
};

static unsigned char blankLine[72];     //Use this when no entry in linked list


static void foo(lineInfo_t * lineAddr) {
    unsigned char * lines[6];

    bool noNext = lineAddr->next==0UL;
    bool noNextNext = true;

    if(!noNext) noNextNext = (lineAddr->next)->next==0UL;
    ...
    //Load the Array
    lines[0] = (unsigned char*)lineAddr->lineBuffer;                        
    lines[1] = (noNext)? blankLine:(unsigned char*)(lineAddr->next->lineBuffer);
    lines[2] = ((noNext||noNextNext)? blankLine:(unsigned char*)(lineAddr->next)->next->lineBuffer);
    lines[3] = (lineAddr->prev==0UL)? blankLine:(unsigned char*)(lineAddr->prev->lineBuffer);
    //Print results
    printf("%08X %08X %08X %08X", lines[0], lines[1], lines[2], lines[3]);
    ...
}

关于为什么这不能正确优化的任何明显信息?

4

2 回答 2

4

我可以想象这可能会发生,因为

 bool noNextNext = (lineAddr->next)->next==0UL;

如果 . 则调用 UB lineAddr->next == NULL。无条件调用这条线的事实可能会使优化器假设lineAddr->next永远不会NULL

于 2013-10-04T12:43:44.670 回答
-1

此错误已存在 2 年以上。我用 GCC ARM 和 GCC AVR 编译器都遇到过它。当您尝试通过索引或结构元素为数组元素分配值时,会发生这种情况。就我而言,唯一的解决方案是将优化级别降低到-O1甚至降低到-O0

于 2013-10-04T12:56:33.907 回答