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