繁体   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