View Full Version : C - trying to dynamically allocate an array of structs...

06-19-2008, 01:14 PM
Afternoon all,
I'm fairly new to programming and new here, so please be gentle..! I'm trying to dynamically allocate an array of structs (actually an array of pointers to structs) and I'm having a world of trouble.
This is my attempt so far:
file: arr_struct.c

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

int main(void)
int num_struct=24;
int i;
el_to_ASIC * block;
el_to_ASIC ** arr_of_ptrs;

block=malloc(num_struct * sizeof(el_to_ASIC));
arr_of_ptrs=malloc(num_struct * sizeof(el_to_ASIC *));

arr_of_ptrs[i]=block+(i * sizeof(el_to_ASIC));
arr_of_ptrs[i]->Mod=i; //insert new block here (see comment below)

return (0);

file: arr_struct.h

#ifndef ARR
#define ARR 1

// Typedefs

typedef struct _el_to_ASIC
unsigned int Mod;
unsigned int ASIC;
unsigned int output_num;
unsigned int e_subband;
} el_to_ASIC;


It does seem to work, but when I run it through valgrind I get lots of invalid write errors. this is part of a larger project, but this code is an 'in vitro' example of the problem I'm having.
I also tried splitting up the memory allocation and assigning to the variables into two seperate blocks (insert:

where I indicate in my comment in the code.) Then I get a segfault caused by an invalid write, and I can't work out why..

I'm sure I must be misunderstanding something---I've read a lot about malloc etc. (oh, and I know I'm not free-ing, that's just to save space in this snippet, I do in the larger program) but can't seem to see where i'm going wrong.

update: p.s. I can't use C++. Not my choice, so pls don't tell me to!

06-19-2008, 04:23 PM
With the double star pointers, you need to malloc the **arr_of_ptrs then go through and allocate each of the 24 pointers, e.g.:

for(x = 0; x < num_struct; x++)

arr_of_ptrs[x] = (struct el_to_ASIC*)malloc(sizeof(struct el_to_ASIC));

Then you can allocate the structs after that (you will have to do another malloc). You could also make it so it did 24 again instead of 1 in my example, if you wanted a 24x24 two dimensional array. (My example gives you a 24x1 array) If you only need a 1D array, just use a single level of indirection.

06-19-2008, 04:48 PM

05-07-2012, 03:54 PM
Your code might be breaking the continuity of the memory. It would depend on the way malloc is implemented by the compiler, but it certainly does not guarantee a single block of memory of size (sizeof(num_struct*struct el_to_ASIC)).