【发布时间】:2016-09-29 16:14:09
【问题描述】:
我有两个函数open_files 和read_bytes。当我只调用open_files 时,一切正常,但如果我之后调用read_bytes,我会在open_files 中遇到分段错误。我使用 gcc 作为编译器。
open_files 是一个通过目录查看并填充包含文件名和字符数组长度的结构的函数。
read_bytes是一个没有代码的函数,只返回1。
文件名结构
struct file_name{
char * name;
int length;
};
主要功能:
int main(int argc, char **argv){
struct file_name ** files;
int file_length;
unsigned char * hex;
long int bytesLength;
printf("CRAP");
getchar();
//Function open_files works if read_bytes function is not called....
if(open_files(files, &file_length) >= 0){
printf("CRAP2");
getchar();
if (read_bytes(hex, &bytesLength, files[0]->name) >= 0){
for(int i = 0; i < bytesLength; ++i){
printf("%X\n",hex[i]);
}
}
}
else{
printf("Something went wrong");
}
printf("%s\n", "Helluuuuuu");
free_memory(files, file_length);
return 0;
}
open_files 函数为目录中的每个文件创建一个 file_name 结构。
int open_files(struct file_name ** files, unsigned int * length){
DIR * dir;
struct dirent * ent;
int count = 0;
if((dir = opendir("TestFiles")) != NULL){
while((ent = readdir(dir)) != NULL ){
++count;
}
count -= 2;
closedir(dir);
}
else{
//Couldn't open directory
perror("");
return -1;
}
printf("working");
getchar();
//Allocate memory
*files = malloc(count * sizeof(struct file_name *));
printf("not working");
getchar();
*length = count;
if((dir = opendir("TestFiles")) != NULL){
count = 0;
while((ent = readdir(dir)) != NULL ){
if(strcmp(ent->d_name,".") != 0 && strcmp(ent->d_name,"..") != 0){
struct file_name * file = malloc(sizeof(struct file_name));
file->name = malloc(strlen(ent->d_name));
strcpy(file->name,ent->d_name);
file->length = strlen(ent->d_name);
files[count] = file;
++count;
}
}
closedir(dir);
}
else{
//Couldn't open directory
perror("");
return -1;
}
return 0;
}
read_bytes 是一个返回 1 的空函数:
int read_bytes(unsigned char * hex, long int * length, char * file){
//FILE * fp;
//*length = file_size(file);
//printf("%li\n",*length );
//fp = fopen("TestFiles/first.jpg", "r");
//fread(hex, 1, *length, fp);
//fclose(fp);
return 1;
}
【问题讨论】:
-
file->name = malloc(strlen(ent->d_name));-->file->name = malloc(strlen(ent->d_name)+1);(+1) 也许还有其他问题。 -
bytesLength 包含我认为的垃圾。您没有存储任何值并将其传递给 for 循环。
-
@chux 我加了 +1 仍然是分段错误
-
@Mazhar 计划 bytesLength 将从 read_bytes 函数中获取其值。
-
你从
main()(files) 传递open_files()一个未初始化的指向指针,然后尝试将 它指向的内容 设置为指向新分配的内存块。这可能会导致访问冲突,如果没有,指针在main()中仍然不可用。 (提示:传递来自main()的指针的地址,而不是(未初始化的)指向指针的值)
标签: c segmentation-fault