2014-08-29 74 views
1

新的C和Valgrind以及手动内存管理,我在定位运行Valgrind时遇到的错误时遇到问题。我有这个功能,从用户获取字符串:无效的读取 - Valgrind和C

char **get_fragments_from_user(){ 
    // No more than 20k strings containing at most 1k characters 
    char **strings = malloc(20000 * sizeof(char *)); 

    char tempstring[MAX_INPUT]; //MAX_INPUT = 1001 
    int count = 0; 
    while(true){ 
     printf("\n> "); 
     fgets(tempstring, MAX_INPUT, stdin); 
     if((strlen(tempstring) > 0) && (tempstring[strlen(tempstring) - 1] == '\n')){ 
      tempstring[strlen(tempstring) - 1] = '\0'; 
     } 
     if(tempstring[0] == 'q') break; 
     strings[count] = malloc(sizeof(char) * (strlen(tempstring)+1)); 
     strcpy(strings[count], tempstring); 
     count++; 
    } 
    int i = 0; 
    char **fstrings = malloc((count)*sizeof(char *)); // count+1 needed? Something I tried removing while debugging 
    for(i = 0; i < count; i++){ 
     fstrings[i] = malloc(sizeof(char) * (strlen(strings[i])+1)); 
     strcpy(fstrings[i], strings[i]); 
     free(strings[i]); 
    } 
    free(strings); 
    return fstrings; 
} 

这里的想法很简单,就是让字符串,把它们放在一个阵列。我最初分配一个足够大的数组来容纳可以输入的最大数量的字符串(20,000),但是我然后调整数组的大小,以便不分配比每个字符串所需的更多的内存。我对上面的代码感到有些尴尬,因为它比我用其他语言写的任何东西都要干净,但这是我第一次通过。

然后我从Valgrind的“大小8的无效读”当我尝试使用此功能来计算数组中的字符串数:

int lengthOf(char **arr){ 
    int i = 0; 
    while(arr[i] != NULL){ 
     i++; 
    } 
    return i; 
} 

我敢肯定,这是由于取消引用指针或其他东西,但我无法在我的生活中找到它,并且我一直在查看此代码一个小时左右。

+0

建议,'字符** fstrings =释放calloc (count + 1,sizeof(char *));' – BLUEPIXY 2014-08-29 00:09:11

+0

Plus:before'return fstrings;' - >>'fstrings [i] = NULL;' – wildplasser 2014-08-29 00:15:10

+0

好吧,那么去计算+ 1并使malloc进入calloc已经摆脱了我所遇到的原始问题,但我现在还有其他一些问题,但是我会先看看能否通过它们。另一个大小为1的无效阅读。 – 2014-08-29 00:15:57

回答

-1

所以,我相信问题是我没有分配足够的内存来存储整个数组。

而不是做的:

malloc(count * sizeof(char *)); 

我应该已经分配计数+ 1,所以无论是:

malloc((count + 1) * sizeof(char *)) 

calloc((count + 1), sizeof(char *)); 
+0

没有明显需要复制每个字符串两次,您可以简单地通过fstrings [i] = strings [i]指定避免malloc,strcpy和free在复制循环中的指针。字符串/ fstrings需要通过NULL条目终止,所以要么使用calloc或malloc赋值给字符串[count] = 0&fstrings [count]。 – Rob11311 2016-02-01 19:04:57