Leonardo Maia
Leonardo Maia

Reputation: 15

Allocing memory to array of strings

So, i'm tring to allocate memory to insert file names in it. I have my struct Estado defined like this:

typedef struct estado{

    char modo;
    char jogador;
    char matriz[8][8];
    int pretas;
    int brancas;
    char *nome[10];
    int current;

} Estado;

I tried doing this:

Estado insereFicheiro(Estado estado , char* nome){

    estado.nome[estado.current] = malloc(sizeof(char*));
    estado.nome[estado.current++] = nome;

    return estado;
}

What am i doing wrong ?

Upvotes: 1

Views: 52

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

There's two problems with the code you show:

  1. With

    estado.nome[estado.current] = malloc(sizeof(char*));
    

    you allocate only space for a pointer, not the whole string. This is like you creating an array of one pointer. You need to allocate space for the string itself, whose length you get from strlen, and also for the null-terminator at the end:

    estado.nome[estado.current] = malloc(strlen(nome) + 1);  // +1 for null-terminator
    
  2. With

    estado.nome[estado.current++] = nome;
    

    you overwrite the pointer you created above. This is equivalent to e.g. int a; a = 5; a = 10; and then be surprised that a is no longer equal to 5. You need to copy the string, not the pointer:

    strcpy(estado.nome[estado.current++], nome);
    

Of course, you need to free the memory you allocate later in your code, once you're finished with it.

And of course you should have some bound-checking to make sure you don't go out of bounds of the estado.nome array (i.e. a check for estado.current < 10).

Upvotes: 2

Related Questions