死C变量

时间:2016-10-05 21:19:56

标签: c callstack

我正在处理一些我无法展示的私人代码,但我已经制作了一些示例代码来描述我的问题:

main.c中:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdint.h>

typedef uint32_t (*FuncPtr)(char *s, uint32_t n);

uint32_t doSomething(char *s, uint32_t n){ 
    printf("n is %d in doSomething\n", n);
    printf("s is '%s' in doSomething\n\n", s);
    return 0;

}

uint32_t func1(char *s, uint32_t n){
    printf("n is %d in func1\n", n);
    printf("s is '%s' in func1\n\n", s);
    return doSomething(s, n);
}

uint32_t func2(char *s, uint32_t n){
    printf("n is %d in func2\n", n);
    printf("s is '%s' in func2\n\n", s);
    return doSomething(s, n);
}

uint32_t func3(char *s, uint32_t n){
    printf("n is %d in func3\n", n);
    printf("s is '%s' in func3\n\n", s);
    return doSomething(s, n);
}

void perform(FuncPtr fp, char *s, uint32_t n){
    printf("fp is location in %p\n", fp);
    printf("n is %d in perform\n", n);
    printf("s is '%s' in perform\n\n", s);
    fp(s, n);
}

int main(void) {

    srand(time(NULL));
    uint32_t r = (uint32_t)(rand() % 3 + 1);
    uint32_t n = (uint32_t)(rand() %100);
    char *s = "some string here";

    printf("r is %d\n", r);
    printf("n is %d in main\n", n);
    printf("s is '%s' in main\n\n", s);

    switch(r)
    {
        case 1:
            perform(func1, s, n);
            break;
        case 2:
            perform(func2, s, n);
            break;
        case 3:
            perform(func3, s, n);
            break;
    }

    return 0;
}

这是调用堆栈:

 0  func1(s=0x9abcdef0, n=0 << Dead >>) [..\main.c:9,1]
 1  perform(fp=0x12345678, s=0x9abcdef0, n=42)  [..\main.c:21,1]
 2  main()  [..\main.c:25,10]

正如您在顶部看到的那样,传递到n的{​​{1}}为func1且与<< dead >>中的值不匹配,即使{{1}指针总是保持在同一个地址上。为什么会这样?我还没有找到有关死变量是什么的有用描述。我是否可以对此代码进行任何修复,或者这是否涉及更多编译器/内存问题,我无法在此处实现?

1 个答案:

答案 0 :(得分:3)

死变量是写入的变量,但从不再读取。编译器可以通过删除此代码进行优化,因为它不会影响结果。