c - 在未使用的符号上获取 SEGFAULT

标签 c lldb llvm-clang

我对 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/

相关文章:

Clang 解析器 - 忽略指令 #ifdef,解析所有内容

ios - 省略了 ObjectiveC 的 clang AST 中的代码块

C 编程 - 矩阵索引 X 和 Y

objective-c - 如何在 iOS 中将数字显示为持续时间的一小时?

C89 和变量初始化

macos - 在 LLDB 中,是否可以在断点处编写一些简单的命令并在没有 python 的情况下自动继续

ios - 为什么我在lldb中输入图像查找<地址>时没有输出?

C数组初始化

c++ - lldb:无法实现:无法获取变量的值

c++ - 在哪里可以找到 Clang-tidy "readability-identifier-naming"检查器的可用选项列表?