0

here is my code

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

struct node {
    char courseID[6];
    int section;
    int credits;
    struct node *link;
};

int main(void)
{
    int run=1;
    char coursetemp[6];
    int option, num, num2;
    struct node *ptr;
    void add(struct node **, int, int, char[]);
    void display(struct node *);
    void del(struct node *, int);

    ptr = NULL;
    while (run==1)
    {
        printf("Main Menu\n 1. Add Course\n2.Delete Course\n3. Display Enrolled courses\n");
        scanf("%d", &option);
        if (option == 1)
        {
            printf("Please enter the course ID\n");
            scanf("%s", coursetemp);
            printf("Please enter the course section, and amount of credits it's worth\n");
            scanf("%d %d", &num, &num2);
            add(&ptr, num, num2, coursetemp);
            display(ptr);
        }
        if (option == 2)
        {
            printf("Enter the element to delete\n");
            scanf("%d", &num);
            del(ptr, num);
        }
        if (option == 3)
        {
            display(ptr);
        }
        else
        {
            //printf("Please enter a proper selection\n");
        }   //end of while
    }
    return 0;
}  
void display(struct node *pt)
{
    while (pt != NULL)
    {
        printf("%s %d %d\n", pt->courseID, pt->section, pt->credits);
        pt = pt->link;
    }
}

This works as I intend it to, as long as the course name is only letters. But as soon as I try it with letters and nums ex. CIS444 I get a bunch of random ascii characters. I feel like it is a simple fix yet I don't recall how to

3
  • 1
    Cannot reproduce, please add input which breaks your program. Commented Mar 28, 2013 at 20:55
  • If there is any numbers in the string, it prints out wrong characters. (ex CIS120) Commented Mar 28, 2013 at 21:01
  • CIS120 is 6 characters long and by that to large for a char[6], since you need to save the termination symbol. You need at least char[7]. Commented Mar 28, 2013 at 21:03

1 Answer 1

1

My suspicion is that you are typing in a course ID of 6 or more characters. The courseID member can only hold a 5 character ID with a null terminator on the end. If, for example, you entered a 6 character course ID, then it would copy 7 bytes into courseID and, depending on structure alignment, overwrite part of the following member in the structure. Note, too, that in this case, the variable coursetemp would also be written past the end (resulting in undefined behavior).

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

1 Comment

+1: This seems to be the problem, since OP stated CIS120 as example input.

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.