c - 我是否会面临缓冲区溢出的风险以及如何避免这种情况?

标签 c string c-strings string-literals

我实现了一个简单的列表结构,其中单个列表元素由以下结构定义:

struct list_elem {
    struct list_elem *next;  // ptr to the next element
    char             *data;  // ptr to data
};

现在,我想做以下事情:

struct list_elem *elem;
int main() {
    elem->data = "some_string";
    strcat(elem->data, "another_string");
}

我担心溢出,因为 strcat 的手册页指出:

The char *strcat(char *dest, const char *src) function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable; buffer overruns are a favorite avenue for attacking secure programs.

基本上我不知道为我的列表元素分配了多少内存。

最佳答案

此声明:

elem->data = "some_string";

使data指针指向字符串文字“some_string”
这里:

strcat(elem->data, "another_string");

您正在尝试将字符串文字“another_string”复制到指向另一个字符串文字的指针。根据标准,尝试修改字符串文字会导致未定义的行为,因为它可能存储在只读存储中。

您应该将内存分配给data,如下所示:

elem->data = calloc(50, 1); // sizeof (char) is 1

然后将“some_string”复制到其中;

strcpy (elem->data, "some_string");

然后将 "another_string" 连接到它:

strcat (elem->data, "another_string");

或者,您也可以使用snprintf():

snprintf (elem->data, 49, "%s%s", "some_string", "another_string");

编辑:

感谢@alk指出这一点。

elem 指针未指向有效内存。 您应该首先为 struct list_elem 指针 elem 分配内存,如下所示:

elem = malloc (sizeof (struct list_elem));
if (elem == NULL)
    exit(EXIT_FAILURE);

关于c - 我是否会面临缓冲区溢出的风险以及如何避免这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53681691/

相关文章:

c - if ('A' <= e <= 'Z' ) 和 if (e > ='A' && e <= 'Z' ) 之间的区别

用于查找带有字符和数字的字符串的正则表达式

string - 错误 : Unterminated character constant beginning at (1)

java字符串替换的最佳方法

C、从输入中读取简单的公式字符串

c - 为什么 C 中的结构指针(方法)比普通函数慢得多?

c - Typedef Struct在C编程中的使用

c++ - 指向 C 字符串的指针?

c++ - 此断点当前不会被命中 : Dll debugging

c++ - 使用 strtok 拆分 C 字符串