1

这段代码不起作用有什么原因吗?

char* toString(struct number *this) {

  char *res;

  if (!this) {
    res = malloc(sizeof(char));
    *res = '\0';
    return res;
  }

  */
    other working code 
  */

}

当我尝试使用 printf 打印时出现“分段错误”:

char *s = toString(NULL); 

printf("%s\n", s);

谢谢。

4

2 回答 2

3

我敢打赌原始来源看起来像这样:

struct number
{
  int i;
}

int main()
{
  char * s = toString(NULL); 

  printf("%s\n", s);

  return 0;
}

char * toString(struct number * this)
{   
  char *res;

  if (!this) {
    res = malloc(sizeof(char));
    *res = '\0';
    return res;
  }

  /*
    other working code 
  */
}

如果是这种情况,那么在之前添加这个原型main()

char * toString(struct number *this);

并且:从现在开始,始终编译所有警告,以免将来再次发生这种情况...... :-)

于 2013-06-23T17:34:35.293 回答
0

如果malloc(1)失败,引用的代码将崩溃。我没有看到任何其他原因。请添加更多代码。

无论如何,只需使用调试器(gdb)。让它崩溃并找到原因......

于 2013-06-23T17:10:03.617 回答