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

Allocating memory and writing (with fread) to string passed as argument to function returning SIGSEGV

关于是什么原因造成的任何线索?这是函数:

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;