启用优化时,阵列无法正确填充GCC ARM

时间:2013-10-04 12:29:36

标签: c arrays optimization gcc

我的代码非常适合在没有优化的情况下从链表的值填充数组。一旦启用优化(-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]);
    ...
}

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

2 个答案:

答案 0 :(得分:4)

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

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

调用UB。无条件地调用此行的事实可能会使优化器认为lineAddr->next永远不会是NULL

答案 1 :(得分:-1)

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