c - 分配内存并写入(使用 fread)作为参数传递给返回 SIGSEGV 的函数的字符串

标签 c string arguments malloc fread

有什么线索可以解释是什么原因造成的吗?这是函数:

int readfile(char** s, const char* filename) {
    struct stat st;
    int i;

    if(stat(filename, &st) == -1)
        return 0;

    *s = malloc(st.st_size+1);
    for (i=0; i<st.st_size+1; i++)
        *s[i] = 0;

    FILE* f;
    f = fopen(filename, "rb");
    fread(*s, 1, st.st_size, f);

    return 1;
}

我是这样调用它的:

char* string;
if (!readfile(&string, "filename.ext"))
    fprintf(stderr, "Problem reading file\n");

我可以轻松地将 fread 读取的内容复制到 readfile 函数内声明的字符串。

提前谢谢您。

最佳答案

这是一个运算符优先级错误:http://www.swansontec.com/sopc.html

我认为你想做的是:

for (i=0; i<st.st_size+1; i++)
  (*s)[i] = 0;

关于c - 分配内存并写入(使用 fread)作为参数传递给返回 SIGSEGV 的函数的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33036770/

相关文章:

c - 如何将具有多个源子目录的 Make 和 Autotools 项目迁移到 CMake?

arrays - 如何在 Swift 中用新行拆分字符串

c++ - bool 表达式习语中的这个字符串文字是什么?

python - 这个宏是如何工作的?

java - 如何将二维字符串数组打印为字符串

c++ - 如何在需要自由函数的地方传递成员函数?

python - 如何获取函数参数类型?

php - 如何将 PHP 函数的参数列表转换为关联数组?

c - rand() 函数错误 : same numbers into a for loop

c - 如何仅使用指针比较字符串的单词词典大小 (aba < ada)