The program crashes when I try to add data to the structure

advertisements

I have a programme that adds new positions to structure list. Structure definition is:

struct data
{
    char name[50];
    char surname[50];
    float income;
    float taxed_income;
    char account[20];
    char id[10];
    struct data *next, *prev;
};

and function that adds data is :

struct data* add_element()

{
    struct data *tmp;
    bool flag=true;
    float input;
    char inpt[50];
    tmp = NULL;
    do {
        printf("Id: ");
        fgets(inpt,49,stdin);
        if(head != NULL)
            flag=id_check(inpt);
    }
    while(!flag);
    strcpy(tmp->id,inpt);
    do {
        printf("Name: ");
        fgets(inpt,49,stdin);
        flag=check(inpt);
    }
    while(!flag);
    strcpy(tmp->name,inpt);
    do {
        printf("Surname: ");
        fgets(inpt,49,stdin);
        flag=check(inpt);
     }
    while(!flag);
    strcpy(tmp->surname,inpt);
    do {
        printf("Account: ");
        fgets(inpt,49,stdin);
        flag=check_num(inpt);
    }
    while(!flag);
    strcpy(tmp->account,inpt);
    printf("Income: ");
    scanf("%f",&input);
    tmp->income=input;
    printf("taxed Income: ");
    scanf("%f",&input);
    tmp->taxed_income=input;
    return tmp;
}

programme crashes when I reach first strcpy. all checks are assuring that input meet project spec.


The pointer to the data structure that you created does not point to anything in memory since it points to NULL. Hence when you try to call the function strcpy() to copy data into the pointer, the program crashes since it is not copying the data to valid memory.

You might want to do some research into the function malloc() which allows you to allocate memory on the heap for your tmp ptr.

Something like this should suffice:

tmp = malloc(sizeof(struct data));

You should also check if the malloc() returned memory that you can use by adding the line:

assert(tmp != NULL);

Note: Don't forget to include the <assert.h> library.