readLines()以换行符结尾。我收到了一些错误,可能是内存问题,有时能用,有时不能。下面是代码:
char* readLine() {
char pom[1000];
gets(pom);
char* s = (char*)malloc(sizeof(char) * strlen(pom));
strcpy(s, pom);
return s;
}下面是readLines()
char** readLines() {
char** lines = (char**)malloc(sizeof(char*));
int i = 0;
do {
char pom[1000];
gets(pom);
lines[i] = (char*)malloc(sizeof(char) * strlen(pom));
strcpy(lines[i], pom);
i++;
} while (strlen(lines[i - 1]) != 0);
return lines;
}大体上,我将这些函数称为
char* p = readLine();
char** lines = readLines();发布于 2021-05-18 00:56:26
当使用malloc为字符串分配内存时,您应该为整个字符串分配足够的内存,包括终止空字符。
在本例中,strcpy将导致buffer overflow,因为目标缓冲区不够大。
你应该改变这行
char* s = (char*)malloc(sizeof(char) * strlen(pom));
至
char* s = (char*)malloc( sizeof(char) * (strlen(pom)+1) );
并更改行
lines[i] = (char*)malloc(sizeof(char) * strlen(pom));
至
lines[i] = (char*)malloc( sizeof(char) * (strlen(pom)+1) );
另外,这一行
char** lines = (char**)malloc(sizeof(char*));
是错误的,因为它只为单个指针分配足够的内存。每行需要一个指针。但是,您可以使用函数realloc根据需要调整缓冲区的大小。
尽管它与您的问题无关,但值得注意的是,函数gets已从ISO标准中删除,不应再使用。建议改用fgets。有关详细信息,请参阅此问题:Why is the gets function so dangerous that it should not be used?
此外,在C中,没有必要强制转换malloc的返回值。这只在C++中是必需的。有关详细信息,请参阅此问题:Do I cast the result of malloc?
在您的代码中,首先使用i++;语句递增i,然后通过减去1重新构造i的先前值
while (strlen(lines[i - 1]) != 0);
这是不必要的麻烦。最好是这样写
while (strlen(lines[i++]) != 0);
并删除行i++;。这样,你就不再需要用1来减去。
https://stackoverflow.com/questions/67573662
复制相似问题