【问题标题】:Split string with delimiter in C - segmentation faults, invalid free在 C 中使用分隔符拆分字符串 - 分段错误,无效免费
【发布时间】:2014-04-24 19:13:58
【问题描述】:

我写了一个简单的代码来用分隔符分割 C 中的字符串。当我删除所有空闲时,代码运行良好,但会导致内存泄漏。当我不删除免费时,它不显示内存泄漏但给出分段错误..什么是wring以及如何解决它?

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

unsigned int countWords(char *stringLine)
{
    unsigned int count = 0;
    char* tmp = stringLine;
    char* last = 0;
    const char delim = '/';

    while (*tmp)
    {
        if (delim == *tmp)
        {
            count++;
            last = tmp;
        }
        tmp++;
    }
    return count;
}

char **getWordsFromString(char *stringLine)
{
    char** sizeNames = 0;
    unsigned int count = 0;
    const char *delim = "/";

    count = countWords(stringLine);

    sizeNames = malloc(sizeof(char*) * count);
    if(sizeNames == NULL)
    {
        return NULL;
    }

    if (sizeNames)
    {
        size_t idx  = 0;
        char* token = strtok(stringLine, delim);
        while (token)
        {
            if(idx > count)
            {
                exit(-1);
            }
            *(sizeNames + idx++) = strdup(token);
            token = strtok(0, delim);
        }
        if(idx == count - 1)
        {
            exit(-1);
        }
        *(sizeNames + idx) = 0;
    }

    return sizeNames;
}

void showWords(char *stringLine)
{
    unsigned int size = countWords(stringLine), i = 0;
    char** sizeNames = getWordsFromString(stringLine);

    for (i = 0; *(sizeNames + i); i++)
    {
        printf("word=[%s]\n", *(sizeNames + i));
        free(*(sizeNames + i));
    }
    printf("\n");
    free(sizeNames);
}

int main()
{
    char words[] = "hello/world/!/its/me/";

    showWords(words);
    return 0;
}

【问题讨论】:

    标签: c string segmentation-fault invalidation


    【解决方案1】:

    变量sizeNames 是一个指针数组,而不是需要以空字符结尾的字符串(字符数组)。

    所以删除这个:

    *(sizeNames + idx) = 0;
    

    然后改变这个:

    for (i=0; *(sizeNames+i); i++)
    

    到这里:

    for (i=0; i<size; i++)
    

    【讨论】:

      【解决方案2】:

      在 getWordsFromString 中,

       *(sizeNames + idx) = 0;
      

      在分配的内存末尾写入一个,当您尝试释放它时,您会遇到段错误。在 malloc 中尝试 count+1:

      sizeNames = malloc(sizeof(char*) * (count+1) );
      

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 1970-01-01
        • 2012-03-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-04
        • 2015-06-29
        相关资源
        最近更新 更多