Reputation: 487
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 M.m[2].A=20
What am I doing wrong? please help.
TY
Upvotes: 0
Views: 253
Reputation: 1305
For more information on the fact that you don't have to cast malloc : Do I cast the result of malloc?
Upvotes: 1
Reputation: 42215
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));
}
Upvotes: 4
Reputation: 9939
void initialize(Model *a, int size)
{
a->m = (node*) malloc(sizeof(node) *size); // NOTICE HERE!!!!
}
Upvotes: 7