【问题标题】:Reserving memory using malloc in C在 C 中使用 malloc 保留内存
【发布时间】:2016-11-11 15:07:22
【问题描述】:

我想为 C 中的 3 个 int 数组保留内存。它们都是 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] = 

我收到分段错误错误。

这里是完整的代码:

#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;
}

谁能解释一下什么是错误,我该如何解决? 非常感谢!

【问题讨论】:

  • 请发送minimal reproducible example。否则我们只能猜测哪里出了问题。
  • a = n; ....c = b + m;...free(c);...请重新阅读C书。
  • @zuma 坦率地说,你的问题我不清楚。
  • m 用作大小和指针?最好贴出真实代码。
  • @zuma 从a = n; 开始...然后整个事情变得不清楚...

标签: c arrays malloc


【解决方案1】:

为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);

【讨论】:

  • 非常感谢!你能解释一下什么是 foo() 和 size_t 吗?
  • @zuma foo()某个函数,它返回一个值以分配a_count, b_count, ...size_t 是最适合用于数组索引和大小去矿化的无符号类型。 int 可能会缩小范围。
  • @zuma 建议避免为不同类型组合分配,如(n + m + m + 1) * sizeof(int) + n * sizeof(pthread_t)。它可行的,但需要额外的代码/检查食物。
猜你喜欢
  • 2012-10-10
  • 1970-01-01
  • 2012-03-09
  • 2019-08-13
  • 2018-10-16
  • 2021-01-18
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
相关资源
最近更新 更多