2014-04-24 70 views
0

我寫了一個簡單的代碼在C與分隔符拆分字符串。當我刪除所有的自由空間時,代碼很好,但是會導致內存泄漏。當我不刪除免費,它不顯示內存泄漏,但給分段錯誤..什麼是絞線和如何解決它?分割字符串在C分隔符 - 分段錯誤,無效免費

#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

可變sizeNames是一個指針數組,而不是字符串(字符數組),你需要用空字符終止。

所以刪除此:

*(sizeNames + idx) = 0; 

並改變這一點:

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

要這樣:

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

在getWordsFromString,

*(sizeNames + idx) = 0; 

寫一個你過去的分配內存的結束,當您嘗試釋放它,你就會得到一個段錯誤。嘗試計數+ 1中的malloc:

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