strcat 和静态分配的字符数组会发生什么情况?

发布于 2024-12-11 03:29:56 字数 362 浏览 0 评论 0原文

我在一些遗留代码中发现了这一点。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你如我软肋 2024-12-18 03:29:56

为什么内存中title2在title1后面?

为什么不呢?该标准不保证物体将放置在哪里。您显示的代码从根本上来说是错误的。 strcat 目标应包含 C 字符串,并且足够大以包含连接的结果字符串。

Why is title2 behind title1 in memory?

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.

陌上青苔 2024-12-18 03:29:56

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文