Split string with delimiter in C - segmentation faults, invalid free

送分小仙女□ 提交于 2019-12-13 05:18:40

问题


I wrote a simple code to split string in C with delimiter. When I remove all my frees, code works great but gives memory leaks. When I dont remove free, it does not show memory leaks but gives segmentation fault .. What is wring and how to solve it?

#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;
}

回答1:


Variable sizeNames is an array of pointers, not a string (array of characters) that you need to terminate with a null-character.

So remove this:

*(sizeNames + idx) = 0;

And change this:

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

To this:

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



回答2:


In getWordsFromString,

 *(sizeNames + idx) = 0;

Writes one past the end of your allocated memory, and when you try to free it, you get a segfault. Try count+1 in the malloc:

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


来源:https://stackoverflow.com/questions/23277830/split-string-with-delimiter-in-c-segmentation-faults-invalid-free

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!