简体   繁体   中英

Dynamic allocation of structs in C

I have a problem with dynamic memory allocation. Here is the code so please help.

#include <stdio.h>
int i;

typedef struct{
  int A;  
}node;


typedef struct Model
        {                            
            node *m;    
        } Model;
        Model M;

void initialize(Model *a, int size)
{
    a->m = (node*) malloc(size);
}


void model_init(Model *a, int len)
{
    int i;
    for (i=0;i<len;i++) a->m[i].A = 20;
}


int main()
{
initialize(&M ,10);
model_init(&M, 10);
for (i=0;i<10;i++) printf("%d\n",M.m[i].A);
}

I am trying to make a Model that has 10 nodes and I want to assign values to nodes in variable A. The printf shows (-1819044973, -1819044973, 14128019, 3969, 0, 0, 0 ...)

I just want it to say for example Mm[2].A=20

What am I doing wrong? please help.

TY

void initialize(Model *a, int size)
{
    a->m = (node*) malloc(sizeof(node) *size); // NOTICE HERE!!!!
}

Your initialize function allocates a number of bytes then model_init later assumes that many node instances will be available. node is larger than 1 byte (at least sizeof(int) bytes) so you write beyond the end of allocated memory.

The easiest fix is to change initialize :

void initialize(Model *a, int elements)
{
    a->m = malloc(elements * sizeof(node));
}

有关不必强制转换malloc的事实的更多信息: 是否可以强制转换malloc 的结果?

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