惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
Stack Overflow Blog
Stack Overflow Blog
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
T
The Blog of Author Tim Ferriss
博客园 - 叶小钗
N
Netflix TechBlog - Medium
腾讯CDC
C
Check Point Blog
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
S
SegmentFault 最新的问题
F
Fortinet All Blogs
美团技术团队
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
F
Full Disclosure
Recorded Future
Recorded Future
D
DataBreaches.Net
博客园 - 【当耐特】
Martin Fowler
Martin Fowler
J
Java Code Geeks
I
InfoQ
Y
Y Combinator Blog
A
About on SuperTechFans
AI
AI
爱范儿
爱范儿
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Forbes - Security
Forbes - Security
W
WeLiveSecurity
M
MIT News - Artificial intelligence
雷峰网
雷峰网
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
Schneier on Security
Schneier on Security
The GitHub Blog
The GitHub Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
Know Your Adversary
Know Your Adversary
Latest news
Latest news
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Docker
Recent Commits to openclaw:main
Recent Commits to openclaw:main
量子位
V2EX - 技术
V2EX - 技术
Project Zero
Project Zero

博客园 - xlander

跟实际生活相关的饭否应用 5个跟实际生活相关的Twitter应用 Google Code上两个LPC21XX开源项目 Router牌音箱 基于ARM的网络收音机 博客程序换成了Z-Blog的 音箱?储钱罐? 显式指针转换的教训 结构体中位段、字节对齐并用的教训 C语言的跨编译器编译 日本某商场里的智能瀑布 ADS下C语言中局部变量的存储位置分配 救活TrackBack的偏方 近期几个开源的嵌入式产品 几个自制心电图的网络资源 哇哦级的贴片焊接教学视频 自动五线谱识别及音乐合成装置 简易指纹识别授权访问系统 PIC18F2550实现的基于HID的USB示波器
使用结构体中成员变量指针的教训
xlander · 2008-09-19 · via 博客园 - xlander

今天碰到的问题,跟这篇文章差不多,也是有关结构体和字节对齐的事儿。

__packed struct _tag_A
{
char a;
char b;
char c;
int d;
};
void Set1(struct _tag_A *p)
{
p->d = 0x12345678;
}
void Set2(int *p)
{
*p = 0x12345678;
}
int main(void)
{
struct _tag_A s;
int i;
while(1)
{
Set1(&s);
Set2((int*)&(s.d));
Set2(&i);
s.d = i;
}
}

上面的代码,用了三种方法,修改结构体_tag_A的成员d。这段代码在VC下面没有测试过,但是在ADS下面,编译和执行都不会报错,但是只有其中的两个执行结果是对的,另外一个是错的,你觉得是那两个呢?

这是我今天刚刚碰到的。问题倒不是什么大问题,却会象陷阱一样潜伏着,成为软件的隐患。

问题发现后,再仔细想想,其实也不难理解。第一、三种方法没有什么问题,第二种方法中,Set2函数的形参是int*,编译器对这个内存的处理默认是4字节对齐的,也就是说丢失了有关结构体的“字节对齐”的信息,而第一种和第三种都保留了这些信息,所以执行的时候也就没有什么问题了。

Copyright © 2008

继续阅读《使用结构体中成员变量指针的教训》的全文内容...

分类: 软件开发 | Tags: 结构体  指针  ARM  C   | 添加评论(0)

相关文章: