I'm trying to learn about the basics in C and I can't quite get malloc()
and free()
to work.
This is my code that's going to print a word in the center of the screen depending on input. (removed some declarations and includes to shorten it)
char *bridge_text;
char menu1[] = "Key input: \n\t n. car arrive north \
\n\t s. car arrive south \
\n\t r. empty bridge \
\n\t q. quit";
int main()
{
bridge_text = malloc(sizeof(char)*(LEN+1)); //misprinted here before
initscr();
getmaxyx(stdscr,row, col);
mvprintw(2, 4, menu1);
refresh();
while(run)
{
switch(getchar())
{
case 'q':
run = 0;
break;
case 'n':
/*not shown: char north[] = "NORTH";*/
bridge_text = north;
break;
case 's':
bridge_text = south;
break;
case 'r':
bridge_text = empty;
break;
default:
bridge_text = empty;
break;
}
mvprintw(row/2, (col-5)/2, bridge_text);
refresh();
}
endwin();
/* adding free() here results in core dump. */
free(bridge_text);
return 0;}
I use gcc with cygwin and the program is executed properly and I can quit the program using 'q'-key, however...
- If first press
'n'
,'e'
or'r'
(assignbridge_text
a string) and then try to exit, it results in a core-dump. This works fine if I removefree()
I do have an error when running executables with cygwin: *
fatal error MapViewOfFileEx shared 5'(0x66) Win 32 error 6.
maybe that's the problem but I assumed it wasn't related to this.