简体   繁体   中英

Pointer to Pointer Segmentation Fault with malloc

I'm using a Pointer to Pointer in my function, but it's not a 2d Array, it's just one string. I tried all kinds of combinations and still can't get it to work, how does this work?

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);
}
There is an error in a way you are trying to print the string. 

The *line is a pointer to array of pointers. each pointer in that array will store a character element. The *line will not be able to print your stored 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM