【发布时间】:2014-06-20 21:03:59
【问题描述】:
我正在编写代码以保存我将在 char *tmp 中读取的内容(get_next_line 的返回是 char *,在 fd 0 上读取) get_next_line 为 char *tmp 分配正确的空间。
所以我将 tmp 保存在 data[i] 中,这是一个 char **,以便将所有输入都保存在 char **data 中。
但我需要 malloc 一个 char **data 但我不知道我需要什么大小。
这段代码有效,但它是 Segfault,因为我没有 malloc char **data。
我知道如何分配一个 char **,但在这里我不知道如何分配它,因为大小不是恒定的。
代码如下:
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
int redirection(char *prev, char *next) {
int b;
char *tmp;
char **data;
int i;
i = 0;
b = 0;
while (b != 1) {
while (strcmp(next, tmp) != 0) {
printf("> ");
tmp = get_next_line(0);
data[i++] = tmp;
}
data[--i] = 0;
i = 0;
while (data[i] != 0)
printf("DATA = [%s]\n, data[i++]");
b = 1;
}
free(tmp);
return (0);
}
这是测试的主要内容:
int main(int ac, char **av) {
if ((redirection("START", "STOP")) == -1) {
printf("REDIRECTION FAIL\n");
return(-1):
}
return(0);
}
【问题讨论】:
-
get_next_line是否分配空间? -
是的,get_next_line完美的为char *tmp分配了正确的空间,没有问题。
-
get_next_line 是什么样子的?
-
char *get_next_line(const int fd) ... ... ... 返回一个 char * malloced 并在 fd 0 上读取直到 '\n'。
-
get_next_line 是否在任何时候都返回 NULL,因为您的逻辑似乎假设了这一点?