我开始学习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;
}
最佳答案
您分配内存,然后用NULL覆盖指针值:
namesPointer[i] = malloc((strlen(directoryEntry->d_name) + 1) * sizeof(char));
if (namesPointer[i] = NULL) {...
应该
if (namesPointer[i] == NULL)
要么
if (!namesPointer[i])