Search code examples
cprintfrealloc

Reallocing a char*


I am trying to do a function that will store in a char array some information to print on it:

int offset = 0;
size_t size = 1;
char *data = NULL;
data = malloc(sizeof(char));

void create(t_var *var){
    size_t sizeLine = sizeof(char)*(strlen(var->nombre)+2)+sizeof(int);
    size = size + sizeLine;

    realloc(data, size);

    sprintf(data+offset,"%s=%d\n",var->name,var->value);
    offset=strlen(data);
}

list_iterate(aList, (void *)create);

t_var is a struct that has two fields: name (char*) and value (int).

What's wrong with this code? When running it on Valgrind it complains about the realloc and sprintf.


Solution

  • Without knowing the specific valgrind errors, the standout one is:

    realloc(data, size); should be data = realloc(data, size);