简体   繁体   English

尝试连接二维数组的元素时出现分段错误

[英]Segmentation fault when trying to concatenate an element of a 2d array

I wanted to use strcat() to concatenate an element of an array of strings.我想使用strcat()连接字符串数组的元素。 I tried:我试过了:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char **str = malloc(sizeof(char *) * 3);

    for (int i = 0; i < 3; i++) {
        str[i] = malloc(sizeof(char) * 8);
    }

    str[0] = "foo";
    str[1] = "bar";

    strcat(str[0], "H");

    for (int i = 0; i < 3; i++) {
        printf("%s\n", str[i]);
    }

    free(str);

    return 0;
}

and I get the error:我得到了错误:

Segmentation fault (core dumped)

What should I do to get it right?我应该怎么做才能让它正确?

For starters the program has memory leaks.对于初学者,该程序有 memory 泄漏。 At first memory was allocated and its addresses were stored in pointers str[i]起初 memory 被分配,其地址存储在指针 str[i] 中

for (int i = 0; i < 3; i++) {
    str[i] = malloc(sizeof(char) * 8);
}

and then the pointers str[0] and str[1] were reassigned by addresses of string literals.然后指针 str[0] 和 str[1] 被字符串文字的地址重新分配。

str[0] = "foo";
str[1] = "bar";

As a result you may not change a string literal by this statement因此,您可能无法通过此语句更改字符串文字

strcat(str[0], "H");

because this invokes undefined behavior因为这会调用未定义的行为

You have to write你必须写

strcpy( str[0], "foo" );
strcpy( str[1], "bar" );

And this loop而这个循环

for (int i = 0; i < 3; i++) {
    printf("%s\n", str[i]);
}

also invokes undefined behavior because the element str[2] was not initialized by a string.还调用未定义的行为,因为元素 str[2] 未由字符串初始化。

Either you need to change the condition or the loop like i < 2 or to initialize the element str[2].您需要更改条件或循环(如i < 2 )或初始化元素 str[2]。

And you need to free all the allocated memory like你需要释放所有分配的 memory 像

for (int i = 0; i < 3; i++) {
    free( str[i] );
}

free( str );

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

相关问题 尝试调整2D阵列大小时出现分段错误 - Segmentation fault when trying to resize a 2D Array 二维数组中的分段错误 - segmentation fault in 2d array 尝试通过指针数组从二维数组打印字符串时出现分段错误 - Segmentation fault when trying to print strings from 2D array via array of pointers 尝试将数组从stdin复制到2d数组时,为什么会出现分段错误? - Why do I get a segmentation fault when trying to copy an array from stdin to a 2d array? 尝试传递递归函数以填充2D数组时出现分段错误 - Segmentation fault on trying to pass a recursive function to populate a 2D array 尝试在C中访问2D数组的地址并出现分段错误 - Trying to access address of 2D array in C and getting segmentation fault 尝试从文件读入二维数组时出现分段错误 - segmentation fault while trying to read in from file to a 2D array 尝试从2D数组中的字符串获取字符时出现分段错误 - Segmentation fault when trying to get a character from a string in a 2D array 尝试将stdin读取到2d动态分配的数组时出现分段错误 - Segmentation fault when trying to read stdin to a 2d dynamically allocated array 尝试对2D char数组使用strcpy()时遇到分段错误? - Getting a segmentation fault when trying to use strcpy() to a 2D char array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM