Search code examples
cmemorycurses

Can't understand these:free immediately after malloc;close file immediately after open


I am reading some source code about an old management tool for bank teller written by c using curses,here are some codes I can't understand:

main(int argc, char *argv[])
{
    int h1, h2;
    char *m1, *m2;
    char fname[100];

    sprintf(fname, "%s/welcome.txt", getenv("xxDIR"));

    m1 = malloc(1);
    free(m1);

    h1 = open(fname, 0);
    if (h1>0) 
        close(h1);
    else 
        fprintf(stderr,"Open first  file : %s \n", strerror(errno));

    func1(argc, argv);

    h2 = open(fname, 0);
    if (h2>0) 
        close(h1);
    else 
        fprintf(stderr,"Open second file : %s \n", strerror(errno));

    if (h1!=h2) 
    {
        fprintf(stderr,"File Open/Close Check: h1=%d, h2=%d\n", h1, h2);
    }

    m2 = malloc(1);
    free(m2);

    if (m1!=m2) 
    {
        printf("Mem  Alloc/Free Check: %ld\n", (long)(m2-m1));
    }       

    exit(0);
}

Like I asked why it free immediately after malloc and close file immediately after open? And func1 is here:

func1(int argc, char *argv[])
{
    char trad_code[5];
    int xx1();
    int xx2();
    int xx3();
    int xx4();
    int xx5();
    int prt_translate(char *fmt, char *data);

    signal( SIGINT, SIG_IGN );

    scr_open();
    clear();
    refresh();

    while ( scr_kbhit() ) scr_getch();

    screen_set_function ( screen_FUNCID_CONFIRM, xx1 );
    screen_set_function ( screen_FUNCID_SETDATA, xx2 );
    screen_set_function ( screen_FUNCID_GETDATA, xx3 );
    screen_set_function ( screen_FUNCID_FLDIN,   xx4 );
    screen_set_function ( screen_FUNCID_FLDOUT,  xx5 );
    prt_set_transfunction ( prt_translate );

    if (sysinit()!=0)   
        goto sysexit;

    Show_Title();
    refresh();

    if (Show_Welcome())
        goto sysexit;

    strcpy(trad_code, "0000");
    do_menu( "0000", trad_code, xxx );

    syskill();

sysexit:

    clear();
    refresh();
    while ( scr_kbhit() ) scr_getch();
    endwin();

    return 0;
}

Solution

  • As stated in my comment, it appears to me that this is a check to see whether func1 is leaking memory or file handles.

    Essentially, the code checks whether allocating memory before and after the call will give back the same memory address, as well as opening a file before and after the call will give back the same file handle.

    If func1 calls malloc but forgets to free the memory again, or it opens a file and doesn't close it again, the values of m1 and m2 or h1 and h2, respecitively, will be different.

    However, this is not a portable approach. It might work on one specific platform, but there is no guarantee that the heap and the file handles will be reused like that on other platforms - they may return different values before and after func1 even if nothing was leaked.