1

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 ?

2
  • You need to specify how long will be the string and change to estado.nome[estado.current] = malloc(20 * sizeof(char) for example. And for assignment use strcpy. Commented Apr 10, 2019 at 12:59
  • @aragon, `sizeof(char) is by definition always 1 in C. Commented Apr 10, 2019 at 15:09

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I would also suggest moving the increment out of the indexing operator, it doesn't have much advantages compared to putting it after the copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.