EAmaral
EAmaral

Reputation: 23

Dynamic Memory Allocation with pointer arrays

I am trying to learn C from tutorials on the web, and I came up with this simple code to try and understand memory allocation on pointers and arrays.

The code compiles and runs flawlessly if size <= 2, but if size > 2 it gives a segmentation error. Can someone please shed a light on how to do this properly?

Thank you.


#include <stdio.h>
#include <stdlib.h>


int main () {


int i, size;

printf("Quantos registos pretende inserir? ");
scanf("%d",&size);
getc(stdin);

typedef struct {
    char nome[81];
    int idade;
    char cargo[81];
} Dados;

Dados *data[(size-1)];

data[(size-1)] = (Dados *)malloc(sizeof(Dados));


for(i=0;i<size;i++) {
    printf("\nInsira os dados do funcionário: ");
    printf("\n\n\tNome: ");
    gets(data[i]->nome);
    printf("\n\tIdade: ");
    scanf("%d",&data[i]->idade);
    getc(stdin);
    printf("\n\tCargo: ");
    gets(data[i]->cargo);

    FILE *fdados;
    if(!(fdados = fopen("dados.txt","a+"))) {
         printf("Impossivel aceder ao ficheiro, verfique o erro ocorrido ...");
    }

    fprintf(fdados, "Funcionário %d:",(i+1));
    fprintf(fdados, "\n\n\tNome: %s",data[i]->nome);
    fprintf(fdados, "\n\tIdade: %d",data[i]->idade);
    fprintf(fdados, "\n\tCargo: %s\n\n",data[i]->cargo);

    fclose(fdados);

}

free(data[(size-1)]);

fflush(stdin);
return(0);
}

Upvotes: 0

Views: 288

Answers (3)

Ion
Ion

Reputation: 334

Well you have a struct, and it seems like you want to create multiple copies of that struct in an array. So what you do is this

Dados *data;
data = (Dados *) malloc(sizeof(Dados) * size);

now you have size number of Dados structures located in data.

then at the end make sure to free your memory free(data);

Upvotes: 1

Lidong Guo
Lidong Guo

Reputation: 2857

remove : getc(stdin);

Dados *data[(size-1)];

data[(size-1)] = (Dados *)malloc(sizeof(Dados));// here is wrong . 
                                                  you have data[size-1]
                                             the max index you can use is size-2



for(i=0;i<size;i++) // i < size-1 , since you use data[i] in loop ,

free(data[(size-1)]); // free (data);  just free the pointer you get.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476950

You're giving yourself way too much to do in one go. Break the problem down and test each component:

  1. Parse user input: Produce either a valid size_t integer or abort. Check that the value is neither zero nor too large, or abort.

  2. Suppose you've parsed the value n. Allocate memory for n copies of your structure:

    Dados * data = malloc(n * sizeof(Dados));
    

    At the end, release the memory:

    free(data);
    
  3. Use proper parsing with error handling to populate each array member data[i].

  4. Practice file operations separately.

Upvotes: 2

Related Questions