gpt4 book ai didi

找不到发生段错误的位置

转载 作者:太空宇宙 更新时间:2023-11-04 05:26:48 25 4
gpt4 key购买 nike

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include "header.h"

char *ROOT = "/home/dereaper/Desktop/shared";

void getFolders (char *PATH, int i) {
const char *path = PATH;
DIR *dir = opendir(path);
struct dirent *entry;
while(entry = readdir(dir)) {
if(!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
continue;
printf("%s/%s INDEX:%d\n", path, entry->d_name, i);
if(entry->d_type & DT_DIR) { //check file type
char *new_path;
strcat(new_path, path);
strcat(new_path, "/");
strcat(new_path, entry->d_name);
getFolders(new_path, i+1); //segmentation fault when calling recursevly

// otherwise the program returns the correct output
}
}
closedir(dir);
}

为什么会出现段错误?

最佳答案

char *new_path;
strcat(new_path, path);

是未定义的行为。

由于 new_path 未初始化且未分配,因此没有可供 strcat 追加的内存。 strcat 附加到一个未确定的地址,创建一个段错误。

关于找不到发生段错误的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22441070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com