Search code examples
csegmentation-faultdynamic-memory-allocationc-stringscalloc

Calloc causes segmantation fault


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;

Solution

  • 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.