[英]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.