我对 C 还很陌生,所以如果我误解了一些基本的东西,请耐心等待
我有一个简单的程序,应该将文件作为字符串读取,然后将该字符串拆分成行 - 将结果存储到 n 个字符串数组中。然而,当我运行以下代码时,我得到了 SEGFAULT - using 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, 0L, 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]);
}
我已经验证文件读取工作正常 - 所以我的字符串分割代码肯定有问题,但我看不出到底出了什么问题
非常感谢任何帮助!
macOS Catalina 15.4,带有 lldb 版本 lldb-1103.0.22.10,使用 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
以及目的地的另一个限制检查。应添加 i < 2048 进行检查。
for(int i = 0; token != NULL && i < 2048; i++) {
destination[i] = token;
token = strtok(NULL, ENDL);
}
关于c - 在未使用的符号上获取 SEGFAULT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63526998/