我已经开始学习C了,我一直在研究一些小程序来学习。现在我正处于记忆指针的位置,我有一个简单的问题。
据我了解,我在下面编写的程序导航到/ proc / sys / net / ipv4 / conf /目录并打印出那里列出的目录。我的目的是在函数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: %i\n", numberOfNames);
int i = 0;
for (i = 0; i <= numberOfNames; i++) {
printf("%s\n", 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("%s\n", directoryEntry->d_name);
strcpy(namesPointer[i], directoryEntry->d_name);
printf("Got to 2\n");
i++;
}
}
closedir(directory);
return numberOfNames;
}
free(namesPointer);
return -1;
}
答案 0 :(得分:0)
您分配内存,然后用NULL覆盖指针值:
namesPointer[i] = malloc((strlen(directoryEntry->d_name) + 1) * sizeof(char));
if (namesPointer[i] = NULL) {...
应该是
if (namesPointer[i] == NULL)
或
if (!namesPointer[i])