【发布时间】:2015-01-04 00:16:01
【问题描述】:
我在嵌入式 C 环境中有以下代码,编译器:Hightec (Big-Endian)
unsigned char GlobalVar;
Func_A()
{
unsigned char var1,Retval;
var1 = 0;
retval = Func_B(0,&var1);
}
unsigned char Func_B (unsigned char val, void* ptr )
{
unsigned long localvar;
localvar = (unsigned long)GlobalVar;
*(unsigned char*)ptr = (unsigned char)localvar;
return (0);
}
输入: 全局变量 = 1 , Func_A 调用 Func_B。
预期输出: Func_B 被调用, 第二个参数更新为值 1。
我所看到的: Func_B 被调用, 第二个参数保存值 64 (0100 0000)。
其他 cmets
1. Func_A is an application file.
2. Func_B is part of a different software module.
3. Func_A reads the value from Func_B to do some action in application.
4. Func_B reads the value from a global variable (it is an array) and copies it into the second argument passed to it.
5. The second argument is a void* because Func_B can read different global variables and finally it would typecast based on parameter 1
(this part is not related, so i have excluded the related code)
你觉得这里发生了什么?
已编辑
重新编辑
抱歉,我匆忙结束了问题
我在这里面临的问题
- var1 是 FUNC_A 的局部变量
- FUNC_B中var1的地址中的值得到更新
- FUNC_B 返回时,var1 的值仍然是旧值。
我是如何解决的
- 我将变量 var1 设为全局变量。
- 我看到数据了
我的怀疑
- var1 是在 FUNC_A 中分配的
- FUNC_A 调用 FUNC_B,分配的空间超出了更新数据的范围
各位专家怎么看?我真的很想知道这种行为的根本原因是什么?
【问题讨论】:
-
请编辑您的问题以包含正确且功能正常的代码,这些代码不会给出编译器错误或警告。最好是Minimal, Complete, and Verifiable example。
-
Func_A 中的 retval 在哪里,您应该使用 Retval.. 这不会编译
-
“真实代码”与您发布的不同,或者您的编译器有错误(可能是前者)
-
嗨,是的,真正的代码是不同的......因为我只能访问其中的一部分并且我没有在代码中看到明显的问题,所以我迅速跳进去看看是否有什么问题在代码中真的很讨厌。看到完整代码后,我可以自己解决问题了
-
@MattMcNabb : 你能检查一下并回复吗?
标签: c casting compilation embedded stack-memory