calloc会导致segmantation故障

发布于 2025-01-28 07:18:59 字数 621 浏览 7 评论 0原文

我正在尝试在我的结构阵列结构中添加一个字符串。我使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝海 2025-02-04 07:18:59

有问题的代码是

varlist.vars[index].called = (char *)calloc(1, sizeof(char) * strlen(var.called));
strcpy(varlist.vars[index].called, var.called);

您正在使用旨在处理字符串的函数的代码 段终止零字符的空间'\ 0'

您必须至少像

varlist.vars[index].called = calloc( strlen(var.called) + 1, sizeof(char) );

var.called一样编写字符串。

因此,还要检查字符串指向指针var.called的代码。

The problematic code is this code snippet

varlist.vars[index].called = (char *)calloc(1, sizeof(char) * strlen(var.called));
strcpy(varlist.vars[index].called, var.called);

You are using functions designed to deal with strings (like strlen and strcpy) 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

varlist.vars[index].called = calloc( strlen(var.called) + 1, sizeof(char) );

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文