簡體   English   中英

char ** 指針中的段錯誤(學習 malloc 和指針用法)

[英]Segfault in a char ** pointer (learning malloc and pointers usage)

我目前正在學習指針和malloc function 的工作原理。 我正在嘗試在 C 中編寫一個 function ,它將一個字符串作為參數。 基本上,它將這個字符串的每個單詞存儲在一個char **ptr中,並且在找到一個空格/制表/'\n' char 時會區分單詞。 例如,字符串“hello world”將存儲為ptr[0] = "hello , ptr[1] = world

到目前為止,這是我寫的:

#include "libft.h"
#include <stdlib.h>


char **ft_split_whitespaces(char *str)
{
    int i;
    int j;
    int k;
    char **tab;

    i = 0;
    j = 0;
    k = 0;
    tab = (char **)malloc(sizeof(char) * 8);
    *tab = (char *)malloc(sizeof(char) * 8);
    while(str[i])
    {
        k = 0;
        while(str[i] == 9 || str[i] == 32 || str[i] == 10 || str[i] == '\0') // if a whitespace or a tabulation or a '\n' char is found, we go further in the string and do nothing
        {
            i++;
        }
        while(str[i] != 9 && str[i] != 32 && str[i] != 10 && str[i] != '\0') // if this isn't the case, we put the current char str[i] in the new array
        {
            tab[j][k] = str[i];
            k++;
            i++;
        }
        if(str[i] == 9 || str[i] == 32 || str[i] == 10 || str[i] == '\0') // now if a new whitespace is found we're going to store the next word in tab[j+1]
        {
            j++;
        }
        i++;
    }   
    return (tab);
}


int     main(void)
{
    char str[] = "  hi im   a       new bie  learning malloc\nusage";
    ft_split_whitespaces(str);
}

請注意,我已經嘗試 malloc 幾個值,但它似乎沒有改變任何東西:當嘗試將單詞“im”(第二個單詞)的字符“i”復制到我的數組中時,它會出現段錯誤。

你們能指導我並告訴我我錯過了什么嗎?

非常感謝提前!

這一行:

    tab = (char **)malloc(sizeof(char) * 8);

只分配 8 個字節來存儲所有指針。 假設 8 是指針的最大數量,它應該是:

    tab = (char **)malloc(sizeof(char *) * 8);

這一行:

    *tab = (char *)malloc(sizeof(char) * 8);

為第一個字分配空間,最多可包含 7 個字符,外加一個 null 終止符。

但是,這只會為tab[0]指向的第一個單詞分配 memory 。 代碼沒有為剩余的字分配任何 memory。

ft_split_whitespaces應該如何表示它從輸入中拆分出來的單詞數? 一種方法是在指向列表中最后一個字的指針之后添加 null 指針。

這是一個工作演示。 它使用strspnstrcspn函數來處理輸入字符串的空白和非空白部分。 它掃描輸入字符串兩次——一次確定字數,一次分配和復制字。 它為空終止的指針列表分配一個 memory 塊,並為每個字分配一個 memory 塊。

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>

/* Free NULL-terminated list of strings. */
void ft_free_strlist(char **strings)
{
    if (strings)
    {
        char **ss = strings;

        while (*ss)
        {
            free(*ss++);
        }
        free(strings);
    }
}

char **ft_split_whitespaces(const char *input)
{
    static const char white[] = "\t\n\v\f\r ";
    size_t nwords;
    size_t i;
    size_t wordlen;
    char **words;
    const char *s;

    /* Determine number of words in input string. */
    nwords = 0;
    s = input;
    s += strspn(s, white);  /* Skip initial whitespace. */
    while (*s)
    {
        /* Found non-whitespace at beginning of word. */
        nwords++;
        s += strcspn(s, white); /* Skip non-whitespace. */
        s += strspn(s, white);  /* Skip whitespace. */
    }

    /* Allocate memory for NULL-terminated list of words. */
    words = malloc((nwords + 1) * sizeof(words[0]));
    if (words != NULL)
    {
        /* Rescan input, allocate and copy words. */
        s = input;
        for (i = 0; i < nwords; i++)
        {
            s += strspn(s, white);  /* Skip whitespace. */
            wordlen = strcspn(s, white);    /* Determine word length. */
            /* Allocate memory for null-terminated word. */
            words[i] = malloc((wordlen + 1) * sizeof(*s));
            if (words[i] == NULL)
            {
                /* Error will be dealt with later. */
                break;
            }
            /* Copy word (source is not null-terminated). */
            memcpy(words[i], s, wordlen * sizeof(*s));
            words[i][wordlen] = 0;  /* Append null terminator to word. */
            s += wordlen;   /* Skip past the copied word. */
        }
        /* NULL-terminate the list of words. */
        words[i] = NULL;
        if (i < nwords)
        {
            /* Could not allocate enough memory.  Free what we got. */
            ft_free_strlist(words);
            words = NULL;   /* Will return NULL later. */
        }
    }
    if (words == NULL)
    {
        /* There was a memory allocation error. */
        errno = ENOMEM;
    }
    /* Return the NULL-terminated list of words, or NULL on error. */
    return words;
}

/* Print NULL-terminated list of strings. */
void ft_print_strlist_const(const char *const *strings)
{
    if (strings)
    {
        while (*strings)
        {
            puts(*strings);
            strings++;
        }
    }
}

void ft_print_strlist(char *const *strings)
{
    ft_print_strlist_const((const char *const *)strings);
}

int main(void)
{
    static const char str[] = "  hi im   a       new bie  learning malloc\nusage";
    char **words;

    words = ft_split_whitespaces(str);
    if (words == NULL)
    {
        perror("Split whitespace");
        return EXIT_FAILURE;
    }
    ft_print_strlist(words);
    ft_free_strlist(words);
    return EXIT_SUCCESS;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM