简体   繁体   中英

C - unsigned int doesn't get the correct value on assignment

This is from gdb:

22      database->size = size;
(gdb) n
23      return database;
(gdb) p size
$6 = 1401
(gdb) p database->size
$7 = 3086862424
(gdb) p &size
$8 = (unsigned int *) 0xbffff050
(gdb) p &database->size
$9 = (unsigned int *) 0xb7fc6ff8

This is from the code:

typedef struct _DATABASE {
    RESULT* res;
    unsigned int size;
} DATABASE;

....
....

DATABASE* alloc_database(unsigned int size, DATABASE* database)
{
    database = (DATABASE*) malloc (sizeof(DATABASE));
    if (!database) return NULL;
    database->res = (RESULT*) malloc (sizeof(RESULT) * size);
    if (!database->res) {
        free_database(database);
        return NULL;
    }
    memset(database->res, 0, sizeof(RESULT) * size);
    database->size = size;
    return database;
}

You can see that both database->size and size are from the (unsigned int) type, in both code and gdb, but for some reason, after the assignment the values are different.

Does anyone knows the what is the reason of that?

database is local to the function alloc_database. You assign to it the result of a malloc, but this assignment is local to the function. After return, database returns to the value it had when the function was called. Note that in gdb, you inspect the value of database->size, AFTER the return. So you inspect it in a scope where the value of database is outside the function.

You have two options:

  1. Change the function to receive only the size argument, allocate to a local and return it. Then you can assign the return value and check it in gdb:

  2. If you want to return a result in the database argument, you need to pass a pointer to the database pointer.

This is the code for option 2:

DATABASE* alloc_database(unsigned int size, DATABASE** database)
{
    *database = (DATABASE*) malloc (sizeof(DATABASE));
    if (! *database) return NULL;
    (*database)->res = (RESULT*) malloc (sizeof(RESULT) * size);
    if (!(*database)->res) {
        free_database((database);
        *database = NULL;
        return NULL;
    }
    memset((*database)->res, 0, sizeof(RESULT) * size);
    (*database)->size = size;
    return (*database);
}

PS אהבה לא באה בחינם...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM