c - 在 C 中使用定界符拆分字符串 - 段错误,无效自由

标签 c string segmentation-fault invalidation

我写了一个简单的代码来使用分隔符在 C 中拆分字符串。当我删除所有释放项时,代码运行良好但会导致内存泄漏。当我不删除 free 时,它​​不会显示内存泄漏但会出现段错误。什么是 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;
}

最佳答案

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

所以删除这个:

*(sizeNames + idx) = 0;

然后改变这个:

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

对此:

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

关于c - 在 C 中使用定界符拆分字符串 - 段错误,无效自由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23277830/

相关文章:

linux - ARM/Linux 上的段错误

c - 卡在执行多线程(Windows 上的 pthread)

c# - Environment.SetEnvironmentVariable 未设置任何值

c - OpenGL 3.3 - glDrawArrays 之后无效操作错误 (1282)

c - 矩阵优化 - 使用内在函数和循环展开时出现段错误

php - Laravel 迁移期间的段错误

c - 为什么 GTK 编译不起作用?

c++ - CPP : Parsing String Stream is too slow

c - 不使用 strrev 函数反转字符串

java - 将字符串分割为前两个空格