![](/img/trans.png)
[英]Why does accessing a member of a malloced array of structs seg fault?
[英]Why does this char array Seg Fault
任何人都可以向我解释为什么初始化char数组时,如果将数组大小留为空白,就像这样
char str1[] = "Hello";
程序将出现段错误,但是如果这样指定
char str1[10] = "Hello";
它工作正常。
这是完整的程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char concat_string(char str[], char str2[], char destination[], unsigned int bufferSize);
int main(int argc, char *argv[])
{
unsigned int bufferSize = 64;
// Both str1 and str2 must be defined
// or else the program will seg fault.
char str1[] = "Hello ";
char str2[] = "World";
char concatenatedString[bufferSize];
concat_string(str1,str2,concatenatedString,bufferSize);
printf("The concatenated string is: \n%s\n", concatenatedString);
return 0;
}
char concat_string(char str[], char str2[], char destination[], unsigned int bufferSize)
{
char buffer[bufferSize];
strncat(str, str2, bufferSize);
strncpy(buffer,str, bufferSize);
strncpy(destination,buffer,bufferSize);
return *destination;
}
您的concat_string
函数中有缓冲区溢出:
strncat(str, str2, bufferSize);
您的str
只有7个字节的空间,在您尝试将str2
附加到它之前,该空间已经满了。 您很幸运:
char str1[10] = "Hello";
因为您仍然没有足够的空间来分配"World"
到它; 您还缺少此版本的str1
的尾随空格,但这与您的段错误无关。 您的concat_string
应该将str
直接复制到destination
,然后将str2
追加到destination
。 这也将避免更改str
和str2
参数,这将更加礼貌。 您也不会传递str
和str1
数组的大小,因此无法知道是否有空间向其添加任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.