gpt4 book ai didi

c - 死 C 变量

转载 作者:太空狗 更新时间:2023-10-29 15:34:49 25 4
gpt4 key购买 nike

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

主.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]

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

最佳答案

死变量是被写入但永远不会被再次读取的变量。编译器可能会通过删除此代码进行优化,因为无论如何它都不会影响结果。

关于c - 死 C 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39883866/

25 4 0
文章推荐: html - 为什么有人想要将表单元素包装在
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com