C looping problem

advertisements

I am writing a simple program in c so I can understand better the language but I have a strange problem. As you see from the code below I have only one loop that it exits when I insert 255 as a value. The problem is that when I select the first(insert option) and after I insert a name the program starts something like a looping and gives me all the time the selection screen...

#include<stdio.h>
#include<stdlib.h>
struct student{
    char *name;
    int id;
    };
void insertStudent(void);
struct student * init(void);    

int main(){
    struct student *p;
    int selectionCode=0;

    while(selectionCode!=255){
        printf("\nInsert students:1");
        printf("\nDisplay students:2");
        printf("\nExit:255");
        printf("\n\nEnter selection:");
        scanf("%d",&selectionCode);

        p=init();

        switch(selectionCode){
            case 1:
            insertStudent();
            //printf("1\n");
            break;
            case 2:
            //printf("2\n");
            break;
            case 255:
            break;
            }
        }

    //p->name="stelios";
    //p->id=0;
    //printf("Name:%s ID:%d",p->name,p->id);
    //free(p);
    //p=NULL;

    return 0;
}
struct student *init(void)
{
    struct student *p;
    p=(struct student *)malloc(sizeof(struct student));
    return p;
}
void insertStudent(void){
    struct student *p;
    p=init();
    printf("Enter Name:");
    scanf("%s",p->name);//return 1;
    printf("Enter ID:");
    scanf("%d",&p->id);
    //printf("test");
    }


Part of the problem may be that the code is not allocating memory for the name field in the structure. The init function allocates a new structure but does not initialize the name field. The insertStudent function then uses scanf to read into that uninitialized pointer. That results in writing to "random" memory and can result in any number of problems including an access violation.