zuma zuma - 28 days ago 7
C Question

Reserving memory using malloc in C

I would like to reserve memory for 3 int arrays in C. All are int types.
Array a is size n, array b is size m and array c is size m.

I have following idea:

void *c;
int *a;
int *b;
int *m;

m = malloc((n + m + m +1) * sizeof(int));
a = n;
b = a + m;
c = b + m;

free(m);


When I try to acces to some of them using syntax for example

a[i] =


I got segmentation fault error.

Here is complete code:

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

void *c;
int *dretve;
int *stol;
int *rez;

int n;
int m;


void *Rezerviraj(void *x){
int c = *((int*)x);
printf("Ušo u funkciju rezerviraj\n");
// sleep(10);
printf("Gotov sam!");
}

int Provjeri(){
int i;
// for(i = n; i < m+n; i++)
// if(stol[i] == 1)
return 0;
return 1;
}



int main(int argc, char *argv[]){

n = atoi(argv[1]);
m = atoi(argv[2]);
int f = 4;

int i = 0;

pthread_t thr_id[2];

c = malloc((n + m + m + 1) * sizeof(int) + n * sizeof(pthread_t));
dretve = n;
stol = dretve + m;
rez = stol + m;

for(i = 0; i < n; i++)
printf("%d ", dretve[i]);

pthread_create(&thr_id[1], NULL, Rezerviraj, &f);
pthread_join(thr_id[1],NULL);

// pthread_create(&thr_id[1], NULL, Rezerviraj,&f);
// pthread_join(thr_id[1],NULL);
// free(c);
return 0;
}


Can someone explain me what is mistake and how can I fix it?
Many thanks!

Answer

To allocate memory for 3 arrays of the same type,

int *a_array;
size_t a_count = foo();

int *ba_array;
size_t b_count = foo();

int *c_array;
size_t c_count = foo();

a_array = malloc(sizeof *a_array * (a_count + b_count + c_count));
b_array = a_array + a_count;
c_array = b_array + b_count;

// code uses a_array, b_array, c_array
... 

// When done with all 3, only 1 free() call
free(a_array);