0

I have the following program in C:

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

typedef struct str{
    char * s;
    int len;
}string;

typedef struct stud{
    unsigned int id;
    string name;
    char gender;
}student;

student* addstud(const int id, const char name[64], const char gender);

student* addstud(void){
    char buf[64]; 
    struct stud *sb;
    sb = (struct stud*)malloc(sizeof(struct stud));

    printf("Enter student ID:\n");
    scanf("%d",&sb->id);

    printf("Enter student name:\n");
    scanf("%s", buf);
    sb->name.s = buf;
    sb->name.len = (int)strlen(buf);

    printf("Enter student gender:\n");
    scanf(" %c", &sb->gender);
    printf("Student ID: %d, name: %s, gender: %c\n", sb->id, sb->name.s, sb->gender);

    return sb;
}

int main(){
    student *mystudent;
    mystudent=addstud();
    printf("Student ID: %d, name: %s, gender: %c\n", mystudent->id, mystudent->name.s, mystudent->gender);
    getchar();
    return 0;
}

In the addstud() function, everthing is fine but in main() when I try to print out the student name from mystudent->name.s it just garbage data. I don't understand why this could happened as it was clearly fine in addstud() function and both pointers point to the same memory address :( Could anyone please shred some light what I did wrong here, please? Thank you!

2

3 Answers 3

2

you can duplicate the buf.

sb->name.s = strdup(buf);
Sign up to request clarification or add additional context in comments.

Comments

1
char buf[64]; 

Here buf is local to function addstud() so once you exit the function this array is out of scope and accessing it will lead to undefined behavior.

Comments

-1
sb->name.s = buf;

In this, buf is a local variable to the function addstud(). So, when the function exits, accessing the variable is UB.

You have 2 options,

1)Either allot memory for buf using malloc()

2) Use strcpy() to copy the contents of the variable buf to sb->name.s

1 Comment

Very detail and precise answer, thank you very much!

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.