gpt4 book ai didi

使用 strcpy 进入数据结构的偏移量时崩溃

转载 作者:行者123 更新时间:2023-12-02 02:09:36 25 4
gpt4 key购买 nike

我在 C 程序中使用了一个特定的数据结构,我用它来将类型信息附加到值。一个简单的示例如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct teststruct
{
char type;
union {
char s;
int i;
float f;
} value;
};

int main()
{
struct teststruct *t = malloc(sizeof(struct teststruct)+10);
t->type = 'i';
t->value.i = 42;
free(t);

t = malloc(sizeof(struct teststruct)+10);
t->type = 's';
strcpy(&t->value.s, "test");

free(t);

printf("Finished without errors.\n");
}

如您所见,我的意图是使用 type 字段来标识值的类型,并使用 value 字段包含可能值的并集。当数据是字符串时,思路是分配比sizeof(struct teststruct)更多的内存,然后用&t->value.s访问字符串。

虽然这可行,但对于优化器来说显然是有问题的。使用 gcc 4.7.2 版,我在非优化条件下得到以下结果:

$ gcc -O0 -o test test.c
$ ./test
Finished without errors.

没问题。然而,在优化器下,它给了我一个警告:

$ gcc -O2 -o test test.c
In file included from /usr/include/string.h:642:0,
from test.c:4:
In function ‘strcpy’,
inlined from ‘main’ at test.c:25:15:
/usr/include/i386-linux-gnu/bits/string3.h:105:3: warning: call to __builtin___memcpy_chk will always overflow destination buffer [enabled by default]

确实,

$ ./test 
*** buffer overflow detected ***: ./test terminated

但是,如果我将 strcpy 替换为 memcpy,这工作正常,如果我将 strcpy 替换为 ,它也可以正常工作>for-循环。但是,strncpy 会像 strcpy 一样崩溃。我绝对不会在 malloc 的内存之外被覆盖,所以我不知道为什么会崩溃。

我意识到复制到数据结构的奇怪偏移量并不常见,所以问题是,我是否违反了 strcpy 的某些语义契约,或者这是编译器中的错误?

谢谢。

最佳答案

您的代码在这里无效:

strcpy(&t->value.s, "test");
// value.s is a single char, not a string that you can store
// an arbitrary number of characters into.
//

你要么需要给 s 一些空间

struct teststruct
{
char type;
union {
char s[10]; // length depends on your specific needs
int i;
float f;
} value;
};

或使 s 成为指针并根据需要动态分配

struct teststruct
{
char type;
union {
char *s;
int i;
float f;
} value;
};
// instead of strcpy(&t->value.s, "test"); use t->value.s = strdup("test")
// don't forget to free the space when you are done.

关于使用 strcpy 进入数据结构的偏移量时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13484734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com