Home > Mobile >  why is my program ending after 1st input?
why is my program ending after 1st input?

Time:09-14

i want to create a program where user will give info as input to form their NID CARD.my program is ending just after taking the first input.i have also used %[^\n] instead of %s, but the same things happen.

#include <stdio.h>

struct DOB
{
        int date;
        char* month;
        int year;
};

struct NID
{
        char* name_bangla;
        char* name_eng;
        char* f_name;
        char* m_name;
        struct DOB s;
        int ID;
};


int main()
{
    struct NID my;
    scanf(" %s", my.name_bangla);
    fflush(stdin);
    scanf(" %s", my.name_eng);
    fflush(stdin);
    scanf(" %s", my.f_name);
    fflush(stdin);
    scanf(" %s", my.m_name);
    scanf("%d", &my.s.date);
    scanf("%[^\n]", my.s.month);
    scanf("%d", &my.s.year);
    scanf("%d", &my.ID);

    printf("name b :  %s\n", my.name_bangla);
    printf("Name : %s\n", my.name_eng);
    printf("father : %s\n", my.f_name);
    printf("mother : %s\n", my.m_name);
    printf("DOB : %d/%s/%d\n", my.s.date,my.s.month,my.s.year);
    printf("ID : %d", my.ID);
}

CodePudding user response:

This line creates an uninitialized object:

struct NID my;

Proceeding to write to the uninitialized pointers in the structure is very wrong. These are wild pointers that almost certainly do not point to memory allocated to the program. These access violations crash your program.

By declaring these fields as arrays by guessing a maximum size (This example uses 16 but you can adjust them to your needs), proper memory is allocated when declaring the variable:

struct DOB
{
        int date;
        char month[16];
        int year;
};
struct NID
{
        char name_bangla[16];
        char name_eng[16];
        char f_name[16];
        char m_name[16];
        struct DOB s;
        int ID;
};

Also make sure the scanf calls do not exceed the allocated memory by adding a limit to the format:

scanf("s", my.name_bangla);
scanf("s", my.name_eng);
scanf("s", my.f_name);
// Etc
  • Related