1

This is a part of a program that ask the user to put students data with interactive choices.

int main(){
    unsigned int choice = 0;
    char new_name[7] = {0};
    unsigned int num_students = 0;
    Student students_list[3] = {0};    // Student is a struct type
    do {
        printf("Press 1 to add a student, 2 to edit an existing student, 0 to exit and print the results.\n");
        printf("Choose option: ");
        scanf("%d", &choice);

        switch (choice){
            case 1:
                printf("Enter the serial number (7 digits): ");
                scanf("%s", new_name);
                students_list[num_students] = create_student(new_name);
                printf("Student added\n");
                num_students += 1;
                break;
            case 2:
                printf("student list:\n");
                for (size_t i=0; i<num_students; ++i){
                    print_results(students_list, &num_students);
                    printf("Choose student id to edit: ");
                }
                break;
            case 0:
                printf("I'm printing the results... I'm printing the results...");
                print_results(students_list, &num_students);
                break;
            default:
                printf("Error, try again.\n");
                break;
        }
    } while (choice != 0);
}

But there must be something wrong.. It's stuck.

Output:

$ ./"strucfirst" 


Press 1 to add a student, 2 to edit an existing student, 0 to exit and print the results.
Choose option: 1
Enter the serial number (7 digits): 1234567

Student added

What am I doing wrong? Is it do_while or switch that makes problems?

Full code (in italian :\ ) if maybe the error could be in other parts of the program: https://hastebin.com/eqayepaquh.cpp

Mnkisd
  • 504
  • 2
  • 12
  • 4
    Your `name` buffer is too small - it needs room for a terminating null, which now, because of overflow, ends up in your `choice` field. – 500 - Internal Server Error May 20 '20 at 18:19
  • You have not shown `print_results()` but are you sure you need to pass a *pointer* to the number of students? – Weather Vane May 20 '20 at 18:24
  • See https://stackoverflow.com/questions/1621394/how-to-prevent-scanf-causing-a-buffer-overflow-in-c. Benign here but buffer overflows can be dangerous! – Alex May 20 '20 at 18:26

0 Answers0