문제

I guess an undefined behavior causes some trouble in my project. To better illustrate my problem, I present a short example below:

#include "stdlib.h"
#include "stdio.h"
#include "stdint.h"

typedef uint32_t ntype_t;

int main(){
    int foo[2] = {0, 1};
    ntype_t a,b;
    int * pt = &foo[1];

    a = 1;
    b = 2;
    printf("%d\n", pt[a-b]);
}

Problem

I compiled this program without any options, and got a Segmentation fault (core dumped). While I compiled this program with -O2, the result was 0. The problem is also relevant with platform, and my environment is Ubuntu linux 3.11.0-15-generic + GCC 4.8.1.

도움이 되었습니까?

해결책

You own the memory pointed to by pt. So you can dereference using *pt. This is equivalent to *(pt + 0) or pt[0].

It turns out that you can reference both pt[0] and pt[-1] since pointer arithmetic is well-defined on your underlying foo array.

But you don't own the memory at pt[a - b] since a - b is not -1 but rather a very large positive number as a and b are unsigned types so the result will be an unsigned type too.

Hence you get undefined behaviour.

Undefined behaviour is exactly that: you can expect anything to happen.

다른 팁

You are subtracting a larger unsigned integer from a smaller one. This causes an ovetflow. The result is a huge number, likely 2^32-1. This index is beyond your array boundaries. That's the UB you are looking for.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top