0

this is my first post, so sorry if it is not asked well.

Basically I am having trouble with dynamic memory and i would like to know if it is me misunderstanding the concept, or at least one of the functions. Ok, so i'm using C++ where I need to manage an array that changes size within the main program loop but i keep getting a heap error when i try to delete the memory. (below is a simplified version of what i'm trying to do).

void main(void)
{
  //Initialization

  //main loop
  while(true)
  {
    int* array;
    function(&array);

    printf("test %d",array[0]); //basically use the data

    delete [] array;
  }
}

//in separate file

void function(**int val)
{
   *val=new int[size of array] // i pass the size of the array...
                               //to the function as well
   //fill the array with data
   return;
}

Ok so after this i can read the data so it must be attached to the pointer "array" but then why would it not allow me to delete the data as if it was already deleted?

Any advice would be much appreciated thanx.

4

4 回答 4

3

不是主要问题,但您实际上这里的语法错误,

void function(**int val);

它应该是:

void function(int **val);

但是您不需要双指针,因为您可以简单地通过引用传递指针:

void function(int *&val);

因此你的程序应该是这样的:

int main() // main should return int
{
    int *array;
    function(array, 5);

    printf("test %d", array[0]);

    delete [] array;
}

void function(int *&val, int size)
{
   val = new int[size];
}

你也不需要while (true)循环。

于 2013-06-03T15:37:17.000 回答
2

您说欢迎“任何建议”,所以这是我的建议:

首先不要使用 C 风格的数组,这不会是一个问题。使用 avector代替:

#include <vector>
#include <algorithm>

void main(void)
{
  //Initialization

  //main loop
  while(true)
  {
      std::vector <int> array;
      function (array);
      printf ("test %d", array[0]);
  }
}

//在单独的文件中

void function(std::vector <int>& vec)
{
  vec.push_back (1);
  vec.push_back (2);
  // ...etc...
}

上面是一个基本且幼稚的实现,它使用 avector而不是 C 样式的数组和动态内存管理。有很多改进的机会,但你明白了。

于 2013-06-03T15:41:39.863 回答
0

您的代码在当前状态下应该可以工作。但是,使用newdelete喜欢这样是非常糟糕的做法,尤其是在不同的地方使用 new/delete

您应该std::vector改用:

// main function 
std::vector<int> array = function();

printf("test %d",array[0]); //basically use the data

你的 function() 将是:

std::vector<int> function()
{
  std::vector<int> val(size);
  //fill the array with data
  return val;
}
于 2013-06-03T15:37:07.057 回答
0

另一个想法。通过引用传递事物的价值是大对象的复制成本。有了指针,您就不必担心这一点。这段代码也可以像这样清理。

int main() // main should return int
{
    int *array = function(SOME_SIZE);

    printf("test %d", array[0]);

    delete [] array;
}

int * function(int size) //Just return the pointer
{
   int *temp = new int[size];
   return temp;
}

由于我们正在处理指针......返回它们并不是什么大问题,当您需要“转移”动态分配对象的所有权时,这是典型的做法。话虽如此,使用向量或其他标准容器引用的帖子是最好的方法。避免使用 new 和 delete 使代码更安全。

于 2013-06-03T15:51:07.917 回答