【问题标题】:Allocating memory and writing (with fread) to string passed as argument to function returning SIGSEGV分配内存并写入(使用 fread)作为参数传递给返回 SIGSEGV 的函数的字符串
【发布时间】:2015-10-09 11:09:35
【问题描述】:

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

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 函数中声明的字符串。

提前谢谢你。

【问题讨论】:

  • memset (*s, 0, st.st_size+1); 而不是 for() 循环可以避免这种情况

标签: c string arguments malloc fread


【解决方案1】:

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

我认为你想要做的是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多