【发布时间】:2021-02-07 20:59:09
【问题描述】:
在下面的函数中,我试图从标准输入读取几个句子,并在用户按两次输入后处理它们。如图所示,我将内存动态分配给整个缓冲区(行集)。我遇到了:
zsh: illegal hardware instruction ./myfunc
最小编译sn-p:
void myfunc(void) {
int textsize = BUF_SIZE;
char **lines = (char **) malloc(sizeof(char *) * textsize);
int linecount = 0;
char text[BUF_SIZE];
while ((strcpy(text, fgets(text, BUF_SIZE, stdin))) != NULL) {
if (text[0] == '\n') {
break;
}
lines[linecount] = (char *) malloc(sizeof(char *) * strlen(text));
strcpy(lines[linecount], text);
linecount++;
}
for (int index = linecount - 1; index >= 0; --index) {
fprintf(stdout, "%s", lines[index]);
/* if line has newline stripped, else printf("%s", lines[index]);*/
}
free(*lines);
exit(0);
}
【问题讨论】:
-
strcpy(text, fgets(text, BUF_SIZE, stdin))当fgets返回NULL时,你认为会发生什么? -
malloc(sizeof(char *) * strlen(text));应该是malloc(sizeof(char) * (strlen(text)+1));因为 C 中的字符串有一个额外的字节用于终止 NUL 字符。sizeof的类型错误,会导致缓冲区过大,但应更改以确保正确性。 -
OT:
exit(0);这在技术上没有错,但通常不是一件好事。函数应该很少导致整个程序退出(一个常见的例外是遇到致命错误)。 -
@kaylum 感谢您的意见! a) 当 fgets 收到 NULL 时,这是否意味着标准输入仅收到两个返回键的 scnario? b)我合并了+1,但不遵循“sizeof 的类型错误”部分。说 BUF_SIZE 是 512,这意味着 512 个指针分别指向每个句子,不是吗? c) 注明。我将其替换为 return 0
-
关于:最小编译sn-p:贴出的代码无法编译!它缺少以下语句:
#include <stdio.h和#include <stdlib.h>和#include <string.h.
标签: c loops for-loop dynamic-memory-allocation c-strings