在 malloc 中使用 sizeof(void)

using sizeof(void) inside malloc

我是 C 的初学者,我面临这个问题:我创建了一个基于快速矩阵分配方法的函数(Oliveira 和 Stewart,"Writing Scientific Software", pag. 94),我想将它用于任何数据类型。 因此,我对其进行了如下更改:

void ** malloc_array2d(size_t m, size_t n){

  /* pointer to array of pointers */
  void ** pointer;
  size_t i;
  /* allocate pointer array of length m */
  pointer = malloc(m*sizeof(void));
  if(pointer == NULL){
    return NULL;
  }
  /* allocate storage for m*n entries */
  pointer[0] = malloc(m*n*sizeof(void));
  if (pointer[0] == NULL) {
    free(pointer);
    return NULL;
  }
  /* set the pointers */
  for (i = 1; i < m; i++) {
    pointer[i] = pointer[0] + i*n;
  }

return pointer;
}

但是我遇到分段错误。

问题是:如何允许不同数据类型的内存分配,因为 sizeof(void) 不起作用(实际上它 returns 只是 1) ? 非常感谢任何反馈。 谢谢

void 不是 pointer 引用的匹配类型。 pointer 引用 void *,而不是 void

通过不对引用类型的大小进行编码,而对取消引用的指针的大小进行编码,避免将来出现错误。

// pointer = malloc(m*sizeof(void));
pointer = malloc(sizeof *pointer * m);

下一次分配,sizeof(void) * m *nnot well defined。代码需要一种新方法。

// pointer[0] = malloc(m*n*sizeof(void));

为各种类型分配,传入数据类型的大小。

void ** malloc_array2d(size_t m, size_t n, size_t data_size){
  ...
  unsigned char *p = malloc(data_size * m *n);
  ...
  for (i = 0; i < m; i++) {
    pointer[i] = p + i*n*data_size;
  }

Sizeof returns 每个数据类型的字节数。 1 表示字节,2 表示 int16,4 表示 int32,等等...然后您可以将它作为参数传递,有任何问题,因为在使用 malloc_2darray 函数时您应该知道要映射的最终数据类型到。

请注意,您总是使用 malloc_2darray 函数,您应该转换为最终数据类型指针,以便正确解释返回的指针。

首先sizeof(void)的值总是1,这里的void指的是无类型数据类型的指针内存分配。我认为任何其他数据类型都不会占用那么少的内存。好吧,int、float 等会消耗更多的数据。如果您希望 sizeof() 的值 return 1,您可以在 malloc() 函数中手动指定大小,而不是使用 sizeof() 功能以及不同的数据类型。