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!

osappuk
  • 41
  • 6

3 Answers3

2

you can duplicate the buf.

sb->name.s = strdup(buf);
Ôrel
  • 7,044
  • 3
  • 27
  • 46
0
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.

Gopi
  • 19,784
  • 4
  • 24
  • 36
-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

Haris
  • 12,120
  • 6
  • 43
  • 70