用malloc指向指针分段错误的指针

时间:2016-10-27 22:01:56

标签: c pointers segmentation-fault malloc

我在我的函数中使用指针指针,但它不是二维数组,它只是一个字符串。我尝试了各种组合,仍然无法使其工作,这是如何工作的?

int get_next_line(const int fd, char **line)
{
    char buffer[BUFF_SIZE];
    int i;

    i = 0;
    *line = malloc(sizeof(char *) * BUFF_SIZE);
    read(fd, buffer, BUFF_SIZE);
    while (buffer[i] != '\n')
    {
    if(!(*line[i] = (char)malloc(sizeof(char))))
        return (0);
        *line[i] = buffer[i];
        i++;
    }
    write(1, buffer, BUFF_SIZE);
    printf("%s", *line);
    return (0);
}

int main()
{
    int fd = open("test", O_RDONLY);
    if (fd == -1) // did the file open?
        return 0;
    char *line;
    line = 0;
    get_next_line(fd, &line);
}

1 个答案:

答案 0 :(得分:-1)

There is an error in a way you are trying to print the string. 

*行是指向指针数组的指针。 该数组中的每个指针都将存储一个字符元素。 *行将无法打印存储的字符串。

Hence use the below code to get the expected results:    

int get_next_line(const int fd, char **line)
    {
        char buffer[BUFF_SIZE];
        int i;

        i = 0;
        *line = malloc(sizeof(char) * BUFF_SIZE);
         if (*line == NULL)
         return 0;        
         read(fd, buffer, BUFF_SIZE);
        while (buffer[i] != '\n')
        {
            *line[i] = buffer[i];
            i++;
        }
        write(1, buffer, BUFF_SIZE);
        printf("%s", *line);
        return (0);
    }

int main()
{
    int fd = open("test", O_RDONLY);
    if (fd == -1) // did the file open?
        return 0;
    char *line;
    line = 0;
    get_next_line(fd, &line);
}