calloc会导致segmantation故障
我正在尝试在我的结构阵列结构中添加一个字符串。我使用GCC(不是clang)在MACOS中编码了这一点,并且工作正常,但是当我将代码导入Windows时,此calloc会导致segmantation故障。
index = varlist.var_count;
varlist.var_count++;
varlist.vars = (Var *)realloc(varlist.vars, sizeof(Var) * varlist.var_count);
varlist.vars[index].called = (char *)calloc(1, sizeof(char) * strlen(var.called));
strcpy(varlist.vars[index].called, var.called);
这是我的结构确定
struct Var
{
int id;
char * called;
void * ptr;
int type;
};
typedef struct Var Var;
struct Varlist
{
int var_count;
Var * vars;
};
typedef struct Varlist Varlist;
I am trying to add a set a string in my struct array's struct. I coded this in Macos using gcc (not clang) and works fine but when i import my code to Windows this calloc causes segmantation fault.
index = varlist.var_count;
varlist.var_count++;
varlist.vars = (Var *)realloc(varlist.vars, sizeof(Var) * varlist.var_count);
varlist.vars[index].called = (char *)calloc(1, sizeof(char) * strlen(var.called));
strcpy(varlist.vars[index].called, var.called);
this is my structs definitation
struct Var
{
int id;
char * called;
void * ptr;
int type;
};
typedef struct Var Var;
struct Varlist
{
int var_count;
Var * vars;
};
typedef struct Varlist Varlist;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有问题的代码是
您正在使用旨在处理字符串的函数的代码 段终止零字符的空间
'\ 0'
。您必须至少像
var.called
一样编写字符串。因此,还要检查字符串指向指针
var.called
的代码。The problematic code is this code snippet
You are using functions designed to deal with strings (like
strlen
andstrcpy
) but the allocated character arrays do not contain strings because they do not reserve space for the terminating zero character'\0'
.You have to write at least like
wherein
var.called
also must contain a string.So check also the code where the string pointed to by the pointer
var.called
is formed.