简体   繁体   English

C - unsigned int在赋值时没有得到正确的值

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

This is from gdb: 这是来自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. 你可以看到数据库 - >大小和大小都来自(unsigned int)类型,代码和gdb,但由于某种原因,在赋值后,值是不同的。

Does anyone knows the what is the reason of that? 有谁知道这是什么原因?

database is local to the function alloc_database. 数据库是函数alloc_database的本地数据库。 You assign to it the result of a malloc, but this assignment is local to the function. 您为其分配了malloc的结果,但此赋值对于函数是本地的。 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. 请注意,在gdb中,在返回之后检查database-> size的值。 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. 更改函数只接收size参数,分配给本地并返回它。 Then you can assign the return value and check it in gdb: 然后你可以分配返回值并在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: 这是选项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 אהבה לא באה בחינם... PSאהבהלא地图בחינם...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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