gpt4 book ai didi

不使用字符串函数连接字符串 : Replacing the end of string (null character) gives seg fault

转载 作者:行者123 更新时间:2023-11-30 20:03:38 24 4
gpt4 key购买 nike

如果不使用 string.h 函数(只想使用 std 库),我想通过连接作为程序参数提供的字符串来创建一个新字符串。为此,我决定将参数复制到一个更大尺寸的新字符数组,然后用我想要附加的字符替换字符串的末尾。

unsigned int argsize=sizeof(argv[1]);
unsigned char *newstr=calloc(argsize+5,1);
newstr=argv[1]; //copied arg string to new string of larger size
newstr[argsize+4]=oname[ns]; //copied the end-of-string null character
newstr[argsize]='.'; //this line gives seg fault
newstr[argsize+1]='X'; //this executes without any error

我相信必须有另一种更安全的方法来连接字符串,而无需使用字符串函数,或者通过将字符逐个复制并附加到新的字符数组中。我真的很想知道这样的方法。另外,我很想知道这个段错误的原因是什么。阅读此处:https://stackoverflow.com/a/164258/1176315我猜,编译器正在使我的空字符内存块只读,但这只是一个猜测。我想知道这背后的真正原因。我将感谢您为回答这个问题所做的一切努力。谢谢。编辑:仅使用 std libs,我的意思是我不想使用 strcpy()、strlen()、strcat() 等函数。

最佳答案

Without using the string.h functions (want to use only the std libs)

string.h 是标准库的一部分。

unsigned int argsize=sizeof(argv[1]);

这是错误的。 sizeof 不会告诉您 C 字符串的长度,它只是告诉您其参数的类型有多大。 argv[1] 是一个指针,sizeof 只会告诉您指针在您的平台上有多大(通常为 4 或 8),而不管该指针的实际内容字符串。

如果你想知道一个 C 字符串有多长,你必须检查它的字符并计数,直到找到 0 个字符(顺便说一句,这就是 strlen 所做的)。

newstr=argv[1];    //copied arg string to new string of larger size

不。您刚刚将argv[1]中存储的指针复制到变量newstr,顺便丢失了calloc的指针之前返回给你,所以你也有内存泄漏。

要将字符串从缓冲区复制到另一个缓冲区,您必须逐个复制其字符,直到找到 0 字符(顺便说一句,这就是 strcpy 所做的)。

因此,以下所有行都在 argv[1] 上运行,因此,如果超出其原始范围,任何事情都可能发生。

I believe there must be another more secure way of concatenating string without using string functions or by copying and appending char by char into a new char array.

C 字符串只是字符数组,一切都归结为一次复制/读取它们。如果您不想使用提供的字符串函数,您最终将不得不自己重新实现它们。请注意,这是一个有用的练习,但您必须更好地理解 C 字符串是什么以及指针如何工作。

关于不使用字符串函数连接字符串 : Replacing the end of string (null character) gives seg fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48603529/

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