[英]What's wrong with this simple code using strings, malloc and strcat?
A char**
always confuses me. char**
总是让我困惑。 The following code generates a segmentation fault. 以下代码生成分段错误。 Explain please...
请解释...
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char** nameList;
nameList = malloc(4*sizeof(char*));
nameList[0] = malloc(12); //not sure if needed but doesn't work either
nameList[0] = "Hello ";
printf("%s ",nameList[0]);// even this statement isn't executed
strcat(nameList[0], "World");
printf("%s ",nameList[0]);
return 0;
}
After nameList = malloc(4*sizeof(char*));
在
nameList = malloc(4*sizeof(char*));
you have: nameList[0] = trash nameList[1] = trash nameList[2] = trash nameList[3] = trash 你有:nameList [0] = trash nameList [1] = trash nameList [2] = trash nameList [3] = trash
After nameList[0] = "Hello ";
在
nameList[0] = "Hello ";
you have nameList[0] = "Hello" nameList[1] = trash nameList[2] = trash nameList[3] = trash 你有nameList [0] =“Hello”nameList [1] = trash nameList [2] = trash nameList [3] = trash
So when you do strcat(nameList[1], "World");
所以当你做
strcat(nameList[1], "World");
it's very likely you'll get a segfault, because nameList[1] can point to anywhere in memory. 你很可能会得到一个段错误,因为nameList [1]可以指向内存中的任何位置。
Your code exhibits undefined behavior by writing to read-only storage, and also attempting to write past the end of it. 您的代码通过写入只读存储来展示未定义的行为,并且还尝试写入它的末尾。
Your malloc
idea was a step in the right direction. 您的
malloc
理念是朝着正确方向迈出的一步。 However, you should use strcpy
to copy "Hello"
into the newly allocated memory. 但是,您应该使用
strcpy
将"Hello"
复制到新分配的内存中。 In addition, you need to consider the size of the string that you are planning to append, and the null terminator when calculating the size of the dynamic allocation. 此外,您需要考虑计划追加的字符串的大小,以及计算动态分配大小时的空终止符。
Obviously, you also need to free all your allocated memory at the end of your program: 显然,您还需要在程序结束时释放所有已分配的内存:
char** nameList;
nameList = malloc(4*sizeof(char*));
nameList[0] = malloc(12);
strcpy(nameList[0], "Hello ");
printf("%s ",nameList[0]);
strcat(nameList[0], "World"); // You were strcat-ing into a wrong element
printf("%s ",nameList[0]);
free(nameList[0]);
free(nameList);
Before using double ptrs, get code that uses a single ptr to work. 在使用双ptrs之前,获取使用单个ptr的代码。 Also, you don't want to "overprogram" simple code.
此外,您不希望“过度编程”简单的代码。 However, if you want to program the usage of a double ptr, start with this code and modify to use double ptrs.
但是,如果要编写double ptr的用法,请从此代码开始并修改为使用双ptrs。
int main()
{
char *nameList;
nameList = malloc(12); // point nameList to 12 bytes of storage
strncpy(nameList, "Hello \0", 7);
printf("%s\n",nameList); // notice no space, its already after hello
strncat(nameList, "World", 5);
printf("%s\n",nameList);
free(nameList);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.