Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
读取无效-Valgrind和C_C_Arrays_Memory_Memory Management_Valgrind - Fatal编程技术网

读取无效-Valgrind和C

读取无效-Valgrind和C,c,arrays,memory,memory-management,valgrind,C,Arrays,Memory,Memory Management,Valgrind,刚接触C和Valgrind以及手动内存管理,我在查找运行Valgrind时遇到的错误时遇到困难。我有一个从用户那里获取字符串的函数: 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]

刚接触C和Valgrind以及手动内存管理,我在查找运行Valgrind时遇到的错误时遇到困难。我有一个从用户那里获取字符串的函数:

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

我很确定这是由于一个未引用的指针或其他原因造成的,但我一辈子都找不到它,我已经看了大约一个小时的代码了

所以,我认为问题在于我没有分配足够的内存来存储整个阵列

而不是做:

malloc(count * sizeof(char *));
我应该分配计数+1,因此:

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


建议,
char**fstrings=calloc(count+1,sizeof(char*))加:在
返回fstring之前-->
fstrings[i]=NULL好的,现在数到+1并将malloc转换为calloc已经解决了我原来遇到的问题,但是我现在遇到了一些其他问题,但是我会看看是否可以先解决它们。另一个大小为1的无效读取。@wildplasser:为什么这样做?我的直觉是,它可以确保lengthOf函数正常工作,但我不能完全确定这是否正确。lengthOf()函数会一直计数,直到它在数组中看到NULL为止。您没有在其中输入NULL,那么应该有NULL吗?显然不需要将每个字符串复制两次,您只需通过fstrings[i]=strings[i]来分配指针,避免malloc、strcpy和free in copy循环。strings/fstrings需要以空条目终止,因此可以使用calloc或malloc,并将赋值给strings[count]=0&fstrings[count]。
malloc((count + 1) * sizeof(char *))
calloc((count + 1), sizeof(char *));