gpt4 book ai didi

c - 如何处理分配的字符串输入?

转载 作者:行者123 更新时间:2023-11-30 16:19:12 26 4
gpt4 key购买 nike

我正在编写一个函数,当我在它的第二个参数中发现问题时,它会连接字符串。这是我的函数的简化版本

struct c_class* _Append_s(void* self, const char* str,const DWord length) // DWord is unsigned int
{
struct c_class* this = self;

this->inStr = realloc(this->inStr, length + this->len);
#pragma warning(disable:4996)
strcpy(this->inStr + this->len, str); // MSVC does an annoying warnings C4996
#pragma warning(default:4996)
this->len += length;

return this;
}

该函数需要 struct c_class*作为输入参数 ( void* self ),a string追加及其 length以字节为单位并返回结构指针(用于连续调用)struct c_class 本身包含一个 char* inStr 和字符串长度。但事实并非如此。

作为输入 _Append_s 可以采用常规 const 字符串 char* in = "some text" , 字符数组 - char in[10]还有分配的字符串 char* inm = malloc(n) .

所以问题是:

1) 我可以以某种方式跟踪分配了哪些字符串并在连接时释放它们吗?最好没有额外的输入,因为它是一个内部函数,我从 int 和 char* 类型的包装器中调用它。

2)也许有一种方法可以将分配的字符串转换为 const 字符串表达式,然后释放内存?

如果第二件事是可能的,那么第一个问题就变得过时了,因为它解决了我需要生成完成的字符串并释放内存的问题,struct c_class*占据

最佳答案

如果你想释放 char 数组,你只需要在 return this; 上面添加 free((char*)str); 但也许我不明白你说得对。

正如 John Humphreys - w00te 在这个答案中指出的那样 https://stackoverflow.com/a/12204279/6911200警告 C4996 的含义是:

The function strcpy is considered unsafe due to the fact that there is no bounds checking and can lead to buffer overflow.

Consequently, as it suggests in the error description, you can use strcpy_s instead of strcpy:

strcpy_s( char *strDestination, size_t numberOfElements,
const char *strSource );

关于c - 如何处理分配的字符串输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55674784/

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