C-进行strcpy时的分割故障



我已经开始学习C,并且我一直在研究一些小程序以学习。现在,我正在使用内存指针,我有一个快速的问题。

据我了解,我在下面写的程序导航到/proc/sys/net/ipv4/conf/conf/directory,并打印出那里列出的目录。我的目的是在函数getSysctlnames((中分配内存,然后在呼叫者main((中对其进行处理。getSysctlnames((还应返回所找到的目录名称的数量。我已经读到,这不是最好的主意(在功能中分配并从呼叫者那里进行交易(,但是我只是想愚弄和学习而不是遵循模式。我的问题是,在运行strcpy函数时,我在第55行中获得了分割故障。我不确定我在做什么错。任何帮助将不胜感激!

int getSysctlNames(char** namesPointer);
int main(int argc, char **argv) {
    char** namesPointer;
    int numberOfNames = getSysctlNames(namesPointer);
    printf("Number of files: %in", numberOfNames);
    int i = 0;
    for (i = 0; i <= numberOfNames; i++) {
        printf("%sn", namesPointer[i]);
        free(namesPointer[i]);
    }
    free(namesPointer);
    return 0;
}
int getSysctlNames(char** namesPointer) {
    int numberOfNames = 0;
    DIR *directory = opendir("/proc/sys/net/ipv4/conf/");
    if (directory) {
        struct dirent *directoryEntry;
        while ((directoryEntry = readdir(directory)) != NULL) {
            if (strcmp(directoryEntry->d_name, ".") != 0 &&
                strcmp(directoryEntry->d_name, "..") != 0) {
                numberOfNames++;
            }
        }
        closedir(directory);
    } else {
        return -1;
    }
    if (numberOfNames == 0) return 0;
    namesPointer = (char**) malloc(numberOfNames * sizeof(char*));
    if (namesPointer == NULL) {
        return -1;
    }
    directory = opendir("/proc/sys/net/ipv4/conf/");
    if (directory) {
        struct dirent *directoryEntry;
        int i = 0;
        while ((directoryEntry = readdir(directory)) != NULL) {
            if (strcmp(directoryEntry->d_name, ".") != 0 &&
                strcmp(directoryEntry->d_name, "..") != 0) {
                namesPointer[i] = malloc((strlen(directoryEntry->d_name) + 1) * sizeof(char));
                if (namesPointer[i] = NULL) {
                    int j = i - 1;
                    while (j >= 0) {
                        free(namesPointer[j]);
                        j--;
                    }
                    free(namesPointer);
                    return 0;
                }
                printf("%sn", directoryEntry->d_name);
                strcpy(namesPointer[i], directoryEntry->d_name);
                printf("Got to 2n");
                i++;
            }
        }
        closedir(directory);
        return numberOfNames;
    }
    free(namesPointer);
    return -1;
}

您分配内存,然后用null覆盖指针值:

namesPointer[i] = malloc((strlen(directoryEntry->d_name) + 1) * sizeof(char));
if (namesPointer[i] = NULL) {...

应该是

if (namesPointer[i] == NULL)

if (!namesPointer[i])

相关内容

  • 没有找到相关文章

最新更新