簡體   English   中英

具有動態內存分配的結構中的指針

[英]Pointers in structure with dynamic memory allocation

我正在嘗試在具有動態內存分配的結構(第一個)中創建一個結構(第二個)。 對於下面的步驟序列(案例 1),在為第一個結構調用 realloc 之前,我為指向第二個結構的指針調用 malloc,在打印成員 (str[0].a1) 的值時,我看到垃圾第一個結構。 如果我在 malloc 之前放置相同的 realloc 代碼(案例 2),則沒有問題。

#include<stdio.h>
#include<stdlib.h>

typedef struct string2_t {
    int a2;
} string2;

typedef struct string1_t {
    int a1;
    string2 * b;
} string1;


string1 * str = NULL;
int size = 0;

string1 test(int val){

    // case 2
    //str = (string1 *) realloc(str, size*sizeof(string1));

    string1 S;
    S.a1 = val;
    size += 1;
    S.b = (string2 *) malloc(2*sizeof(string2));
    S.b[0].a2 = 11;
    S.b[1].a2 = 12;

    // case1
    str = (string1 *) realloc(str, size*sizeof(string1));
    
    return S;
}

int main() {
    size += 1;
    str = (string1 *) malloc(size*sizeof(string1));
    str[0] = test(10);
    printf("value of a:%d\n",str[0].a1);
    str[1] = test(20);
    printf("value of a:%d\n",str[0].a1);
    return(0);
}

我可以看到情況 1 的內存位置發生了變化,但我不太明白為什么指針沒有指向正確的內容(str[0].a1 顯示垃圾)。 在realloc之前我還沒有返回第一個結構的地址,所以我覺得它應該可以工作。 有人可以解釋為什么它指向垃圾嗎?

正如評論中的一些人所說,像這樣的行會導致未定義的行為:

str[0] = test(10);

test()函數重新分配str ,這與檢索str[0]的地址作為存儲結果的位置無關。 很有可能編譯出來就好像寫過一樣

string1 *temp = str;
temp[0] = test(10);

temp緩存了realloc()之前str的舊地址,函數返回后無效。

將您的代碼更改為:

string1 temp = test(10);
str[0] = temp;

更好的設計是重新組織代碼,以便在一個地方完成str數組的所有維護。 test()應該是一個只分配string1對象的黑盒子,而main()在分配給它時分配並重新分配str

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM