在不使用字符串函数的情况下连接字符串:替换字符串的结尾(空字符)会导致段错误

Concatenate strings without using string functions: Replacing the end of string (null character) gives seg fault

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

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

我相信必须有另一种更安全的方法来连接字符串,而无需使用字符串函数或通过逐个字符地复制和附加到新的字符数组中。我真的很想知道这样的方法。另外,我很想知道这个段错误的原因是什么。 阅读此处: 我猜,编译器正在将我的空字符内存块设置为只读,但这只是一个猜测。我想知道这背后的真正原因。 我将感谢您为回答问题所做的一切努力。谢谢。 编辑:通过仅使用标准库,我的意思是说我不想使用 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 字符串只是字符数组,一切都归结为 copying/reading 它们一次一个。如果您不想使用提供的字符串函数,您最终将不得不自己重新实现它们。请注意,这是一个有用的练习,但您必须更好地理解什么是 C 字符串以及指针的工作原理。

首先sizeof(argv[1])不会return字符串的长度你需要使用loops或者使用标准库函数[来计算字符串中的字符数=12=].second如果你想复制你需要使用strcpy()函数的字符串。

你应该这样做:

unsigned int argsize=strlen(argv[1]);  //you can also count the number of character
unsigned char *newstr=calloc((argsize+5),1);
strcpy(newstr,argv[1]);    
newstr[argsize+4]=oname[ns];    
newstr[argsize]='.'; 
newstr[argsize+1]='X';