我想为c中的3个int数组保留内存。数组a的大小为n,数组b的大小为m,数组c的大小为m。
我有以下想法:
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);
当我试图使用语法访问其中一些时,例如
a[i] =
I got segmentation fault error.
完整代码:
#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 rezervirajn");
// 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;
}
谁能告诉我什么是错误,我怎么能解决它?很多谢谢!
为3个相同类型的数组分配内存,
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);