在运行时分配内存

时间:2012-01-09 11:11:38

标签: c++ c memory-management

我想知道如何在不使用malloccalloc函数的情况下在C或C ++中以运行时分配内存块。

8 个答案:

答案 0 :(得分:6)

在C中,使用malloc。使用后不要忘记free

在C ++中,使用new并且不要忘记delete。或者更好的是,如果你想要一个动态数组,请使用std::vector

答案 1 :(得分:3)

在C中,使用VLA ...

/* fill an array, allocated dinamically without malloc,
** with 1, 2, 3, 4, ...
** then sum all of the values and print the result */
#include <stdio.h>

void vlaalloc(size_t nmemb, size_t siz, void (*fx) (void *, size_t)) {
  unsigned char data[nmemb * siz];

  fx(data, nmemb);
}

int arraysum(int *arr, size_t len) {
  int val = 0;
  for (size_t i = 0; i < len; i++) val += arr[i];
  return val;
}

void seq(void *data, size_t len) {
  int *arr = data;
  for (size_t i = 0; i < len; i++) arr[i] = i + 1;
  printf("array sum is %d\n", arraysum(arr, len));
}

int main(void) {
  int n;

  if (scanf("%d", &n) == 1) {
    vlaalloc(n, sizeof (int), seq);
  }
}

请参阅code running at ideone

答案 2 :(得分:2)

C中的malloc或C ++中的new

答案 3 :(得分:2)

在C中使用malloc()

int *a = malloc (sizeof(int) * block_size);

在C ++中使用new

int *a = new int[block_size];

注意:此代码使用原始指针。 C ++ 11有更好的指针,如unique_ptrshared_ptr。通常优先考虑这些智能指针而不是原始指针。

编辑:OP需要一个块,所以我正在更新代码

答案 4 :(得分:1)

除非我忽略了你的问题,否则你只需要使用C ++语言标准结构:new和delete / delete []。

答案 5 :(得分:0)

在C中你可以使用:

malloc() 

在C ++中:

malloc()
calloc()

在C ++中,最好使用new-operator。

答案 6 :(得分:0)

我不确定你的问题,但简单的答案是使用

C:

malloc();

C ++:

new

这将返回指向内存的指针,操作系统将负责为您找到它。

答案 7 :(得分:0)

在C中,所有的内存分配都是通过malloc(规则中的内容)来完成的,所以如果你想要malloc以外的东西,那么它取决于你使用的平台,并且你不需要&#39 ; t。说。

在Linux上,mmap可能会做你想要的。毫无疑问,Windows还有别的东西。

在某些系统上,只要您知道所有内容的位置,您就可以在不询问的情况下抓取它,但这主要仅适用于使用基本(或不使用)操作系统的嵌入式系统。

相关问题