c++ - Why don't ncurses widgets work properly when created in a separate function? -


i'm trying create series of nested menus using pure ncurses in c++. if create menu , post in main(), works fine. if take same code , put in function returns menu*, doesn't work @ all. missing something?

code works:

int main()  {   /*    * snipped out curses startup code    */    vector<char*> options;   options.push_back("list");   options.push_back("add");   options.push_back("delete");   options.push_back("exit");    vector<item*> menu_items(options.size());   (int = 0; < options.size(); i++)     menu_items[i] = new_item(options[i], null);    menu *options_menu;   options_menu = new_menu(&menu_items[0]);    set_menu_win(options_menu, main_window);   set_menu_sub(options_menu, derwin(main_window, 6, 20, 3, 3));   set_menu_mark(options_menu, ">");    refresh();   post_menu(options_menu); // works fine   wrefresh(main_window);   /*     * snipped out rest of stuff    */ } 

code doesn't work:

menu *make_menu() {   /*    * same code in previous main()    */    return options_menu; }  int main() {   /*    * snip    */    menu *options_menu = make_menu();   refresh();   post_menu(options_menu); // doesn't   wrefresh(main_window);    /*    * snip    */ } 

i'll answer future searchers. turns out new_menu takes pointer item list , hangs onto it. if item list on stack of function, it'll deleted when function returns, making item list invalid.

the solution problem create item list on heap, either via new in c++, or using malloc (remember delete or free!). option wrap menu in class , keep item list member variable.

the simplest solution make menu (or item list) global.


Comments