简体   繁体   English

为什么此char数组出现Seg Fault

[英]Why does this char array Seg Fault

Can anyone explain to me why when initializing a char array, if the array size is left blank, like this 任何人都可以向我解释为什么初始化char数组时,如果将数组大小留为空白,就像这样

char str1[] = "Hello";

the program will seg fault, but if it is specified like this 程序将出现段错误,但是如果这样指定

char str1[10] = "Hello";

it works fine. 它工作正常。

Here is the full program 这是完整的程序

#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;
}

You have a buffer overflow right here in your concat_string function: 您的concat_string函数中有缓冲区溢出:

strncat(str, str2, bufferSize);

Your str only has room for seven bytes and it is already full before you try to append str2 to it. 您的str只有7个字节的空间,在您尝试将str2附加到它之前,该空间已经满了。 You're getting lucky with this: 您很幸运:

char str1[10] = "Hello";

as you still don't have enough space allocated to append "World" to it; 因为您仍然没有足够的空间来分配"World"到它; you're also missing the trailing space on this version of str1 but that's not relevant to your segfault. 您还缺少此版本的str1的尾随空格,但这与您的段错误无关。 Your concat_string should be copying str directly to destination and then appending str2 to destination . 您的concat_string应该将str直接复制到destination ,然后将str2追加到destination This would also avoid altering the str and str2 arguments and that would be more polite; 这也将避免更改strstr2参数,这将更加礼貌。 you also don't pass the sizes of the str and str1 arrays so there's no way to know if there is room to append anything to them. 您也不会传递strstr1数组的大小,因此无法知道是否有空间向其添加任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM