我实现了一个简单的列表结构,其中单个列表元素由以下结构定义:
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 thesrc
string to thedest
string, overwriting the terminating null byte ('\0') at the end ofdest
, and then adds a terminating null byte. The strings may not overlap, and thedest
string must have enough space for the result. Ifdest
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/