问题描述
我对C还是很陌生(仍然),所以如果我误解了一些基本知识,请耐心等待
我有一个简单的程序,该程序应将文件读取为字符串,然后将该字符串分成几行-将结果存储到n个字符串数组中。但是,当我运行以下代码时,我得到一个SEGFAULT-使用lldb表示,尽管我的代码中未使用该函数,但libsystem_platform.dylib库中使用strlen时却发生了这种情况。
这是完整的FileIOTest.c文件:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define ENDL "\n"
void read_file(const char* path,char** destination) {
FILE *file;
long size_in_bytes;
file = fopen(path,"r");
if(file == NULL) {
fputs("Requested file is invalid",stderr);
exit(-1);
}
fseek(file,0L,SEEK_END);
size_in_bytes = ftell(file);
fseek(file,SEEK_SET);
fread(*destination,sizeof(char),size_in_bytes,file);
fclose(file);
}
int main() {
char* file = calloc(1024,sizeof(char));
read_file("run",&file);
char* destination[2048];
char* token = strtok(file,ENDL);
for(int i = 0; token != NULL; i++) {
destination[i] = token;
token = strtok(NULL,ENDL);
}
for(int i = 0; i < 2048; i++)
printf("%s",destination[i]);
}
我已经验证了文件读取的有效性-因此,我的字符串拆分代码肯定存在问题,但是我看不出到底是什么错误
我们非常感谢您的帮助!
带有lldb版本lldb-1103.0.22.10的macOS Catalina 15.4,使用clang版本clang-1103.0.32.62编译
解决方法
您必须确保不超过目标大小。 -1表示空字符。
fread(*destination,sizeof(char),min(size_in_bytes,destinationSize - 1),file);
destination [i]不以空字符结尾。您不能将其用作printf的参数
for(int i = 0; i < 2048; i++)
printf("%s",destination[i]); // can cause SEGFAULT
和另一个极限检查目的地。我
for(int i = 0; token != NULL && i < 2048; i++) {
destination[i] = token;
token = strtok(NULL,ENDL);
}
,
结果显示,当您使用%s时,printf调用在后台出现strlen-切换到fputs可解决此问题