C: Function returning a pointer to struct, only works with malloc, why? -


this question has answer here:

i'm total beginner c (obviously), , thought functions inita , initb interchangeable, since both return pointer object of type list (a custom struct) inita produces expected output.

how inita different initb ?

list *inita() {      list *list = malloc(sizeof(*list));     element *element = malloc(sizeof(*element));      element->number = 0;     element->next = null;     list->first = element;       return list; }   list *initb() {     element _el = {.number=0, .next=null};     element *el = &_el;     list _list = {.first=el};     list *list = &_list;     return list; } 

here full source code (trying reproduce first steps of linked list here, pedagogic reasons)

#include <stdio.h> #include <stdlib.h>   typedef struct element element; struct element {     int number;     element *next; };   typedef struct list list; struct list {     element *first; };     list *inita() {      list *list = malloc(sizeof(*list));     element *element = malloc(sizeof(*element));      element->number = 0;     element->next = null;     list->first = element;       return list; }  list *initb() {     element _el = {.number=0, .next=null};     element *el = &_el;     list _list = {.first=el};     list *list = &_list;     return list; }     void printlist(list *list){      element *el = list->first;     while (null != el) {         printf("number: %d, next: %p\n", el->number, el->next);         el = el->next;     }  }  int main(int argc, char *argv[]) {      /**      * output:        * number: 0, next: 0x0      */ //    list *list = inita();      /**      * output:            * number: 1344951776, next: 0x7fff502a55d0      * number: 1344951776, next: 0x29502a55e0      */     list *list = initb();     printlist(list);      return 0;  } 

initb returns pointer locale variable, has scope limited initb. can happen memory located @ address when exit function. such, undefined behavior


Comments