strcat 和静态分配的字符数组会发生什么情况?
我在一些遗留代码中发现了这一点。
static char title1[] = "SUMMARY REPORT";
static char title2[] = "PERIOD: ";
...
strcat(title2, "10/10/2011");
此 strcat 操作会导致 title1 被部分日期字符串覆盖。我能够在一个小程序中重现这一点,但不能使用静态数组。我查看了遗留代码中的内存位置,title2 缓冲区位于 title1 之前。修复很简单,我只是向 title2 添加了一个长度(这将 title1 的开头进一步推入内存)以保存整个日期。为什么内存中title2在title1后面?顺便说一句,这是在 SPARC 上。
I found this in some legacy code.
static char title1[] = "SUMMARY REPORT";
static char title2[] = "PERIOD: ";
...
strcat(title2, "10/10/2011");
This strcat operation results in title1 being overwritten with part of the date string. I was able to reproduce this in a small program, but not with static arrays. I looked at the memory location in the legacy code and the title2 buffer is located just prior to title1. The fix was simple, I just added a length to title2 (which pushed the start of title1 further in memory) to hold the entire date. Why is title2 behind title1 in memory? This is on a SPARC, btw.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不呢?该标准不保证物体将放置在哪里。您显示的代码从根本上来说是错误的。
strcat
目标应包含 C 字符串,并且足够大以包含连接的结果字符串。Why not? The standard makes no guarantees on where will the objects lay. The code you show is fundamentally wrong.
strcat
destination should contain a C string, and be large enough to contain the concatenated resulting string.strcat
假设您传入的缓冲区足够大,可以容纳连接的字符串,如果缓冲区太小,它将覆盖缓冲区的末尾。因此缓冲区后面的任何内容都会被覆盖。strcat
assumes the buffer you pass in is large enough to hold the concatenated string, and it will overwrite over the end of your buffer if it's too small. So whatever behind your buffer gets overwritten.