1

I need to understand why give this error message "stop working". Here is my code.

#include <stdio.h>

struct student{
    int id;
    char name[20];
    char *title;
};

int main()
{
    struct student *st;
    st->id = 23;
    //st->name = "shaib";
    st->title = "title";

    printf ("%d", st->id);
    printf ("%s", st->title);

    return 0;
}

4 Answers4

4

You define a pointer but it is not init, so is Undefined Behavior.

You can create a space in heap memory using malloc function.

int main()
{
    struct student *st = malloc(sizeof(struct student));

    if ( st != NULL)
    { 
       st->id = 23;
       ..
    }
    else
    {
       fprintf(stderr, "No space for variable\n");
    }

    free(st);
    return 0;
}

As you can see, each time you allocate memory with malloc you are responsible for freeing it. Otherwise you have memory leak

Second problem is that

 st->name = "shaib";

is not the way you fill an array with a C-String.

You can achieve it with:

 strcpy(st->name, "shaib");
Community
  • 1
  • 1
LPs
  • 16,045
  • 8
  • 30
  • 61
  • `st->title` is declared as `char *title;`, so st->title = "title" is appropriate, and using strcpy is not appropriate unless you first malloc some space for the pointer. – FredK Jul 01 '16 at 14:49
  • @FredK oooops, I confound it with `name[20]` Thanks. – LPs Jul 01 '16 at 14:51
3

So, you need to allocate some memory for your new struct:

1) Add a #include in order to...

2) Replace the struct declaration for a malloc()

Tip: use a better format for your print outputs with \t and \n

Here's the working code:

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

struct student{
    int id;
    char name[20];
    char *title;
};

int main()
{
    struct student *st = malloc(sizeof (struct student));
    st->id = 23;
    //st->name = "shaib";
    st->title = "title";

    printf ("%d\t", st->id);
    printf ("%s\n", st->title);

   return 0;
}
2

You're creating a pointer to the student structure, but you're not setting it to point to anything.

You'll need to allocate memory for st (the student structure) before you can use it.

Simon Bosley
  • 1,114
  • 3
  • 18
  • 41
  • 1
    Thanks. If I create non-pointer object it works fine, but why ? I did not understand. –  Jul 01 '16 at 14:12
  • Hi @coder_hasib If you create a local variable then it will be created on the stack and available to use within the current scope (i.e. the stack takes care of it for you). If you decide to dynamically allocate the memory on the heap for the structure (using malloc) then you need to keep a pointer to that memory location so that you can deference it when necessary (access it's value). – Simon Bosley Jul 01 '16 at 14:33
2

You are not allocating memory for st.

You can do it like this: st = malloc(sizeof (student));

LPs
  • 16,045
  • 8
  • 30
  • 61
SurvivalMachine
  • 7,946
  • 15
  • 57
  • 87