为什么要修改内存地址?

时间:2014-07-29 15:58:39

标签: c gtk

我有这段代码:

printf("%p\n", gameGUI);
printf("label %p\n", gameGUI->labelRoundType);
gui_setRoundType(gameGUI->labelRoundType,
                 gameGUI->game->rounds[roundId]);
printf("label %p\n", gameGUI->labelRoundType);
printf("%p\n", gameGUI);

函数gui_setRoundType的代码。

int gui_setRoundType(GtkWidget *roundTypeLabel, struct Round *round)
{
    if (round == NULL)
        return ROUND_NULL;
    if (roundTypeLabel == NULL)
        return POINTER_NULL;

    char type[1] = { '\0' };
    intToChar(round->roundType, type);
    gtk_label_set_text(GTK_LABEL(roundTypeLabel), type);

    return NO_ERROR;
}

GameGUI结构的代码:

struct GameGUI {
    struct Game *game;
    struct Select *select;
    struct PlayerCards *playerCards;
    struct PlayersGUI *playersGUI;
    struct CardsFromTable *cardsFromTable;
    struct BidGUI *bidGUI;
    GtkWidget *windowTable;
    GtkWidget *fixedTable;
    GtkWidget *buttonShowScore;
    GtkWidget *imageTrump;
    GtkWidget *labelRoundType;
    GtkWidget *labelNoOfBids;
    GtkWidget *buttonStart;
    int bidPlayerId;
    int cardPlayerId;
};

我的问题是:为什么在所谓的gui_setRoundType()之后修改gameGUI变量的内存地址?

输出示例:

0x1e8ff80
label 0x1e9dd50
label 0xcf9
0x1e8ff00

这是intToChar函数的代码。

int intToChar(int number, char *string)
{
    int i, copy, j;
    char ch;

    if ((copy = number) < 0)
        number = -number;

    i = 0;
    do {
        string[i++] = number % 10 + '0';
    } while ((number /= 10) > 0);

    if (copy < 0)
        string[i++] = '-';
    string[i] = '\0';

    for (i = 0, j = strlen(string) - 1; i < j; i++, j--) {
        ch = string[i];
        string[i] = string[j];
        string[j] = ch;
    }

    return NO_ERROR;
}

1 个答案:

答案 0 :(得分:6)

您在intToChar函数中有缓冲区溢出 - 您将长度为1的缓冲区type传递给它,并且您可能在该函数中写出此缓冲区的边界。这会触发未定义的行为,并且指针开始随机变化。