5 Replies - 1152 Views - Last Post: 03 November 2013 - 04:54 AM Rate Topic: -----

#1 quim  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 18
  • View blog
  • Posts: 182
  • Joined: 11-December 05

Runtime error with dynamic memory allocation

Posted 13 October 2011 - 12:43 PM

i haven't programmed in C++ in a while. now I'm back doing some basic code, and following examples on the book.
The code bellow is suppose to create a dynamic array:
ask the user for the size and dynamically allocated space for the array in the memory.
the code compiles fine but when i run it i get a run-time error when it tries to display the values in the array.

Can someone explain to me what i am doing wrong? i don't want to use vectors i just want to see the concept of dynamic memory allocation.

#include <iostream>
#include <ctime>
#include <cstdlib>


using namespace std;


void fillArray( int* array, int size)
{

    array = new int[size];

    // seed the random number
    srand(time(0));

    for( int i = 0; i < size; i++)
    {
        array[i] = rand() % 100;
    }
}


int main()
{
    int* array = 0;
    int size;

    cout << "Enter the size of the array: ";
    cin >> size;

    cout << "Creating array and filling it with random numbers...\n";

    // filling array
    fillArray( array, size );


    cout << "\nArray = { ";

    for(int i = 0; i < size; i++ )
    {
        cout << array[i] << " ";
    }

    cout << "}\n";

    // free up the memory, avoid leaking...
    delete[] array;
}



Is This A Good Question/Topic? 0
  • +

Replies To: Runtime error with dynamic memory allocation

#2 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 857
  • View blog
  • Posts: 2,340
  • Joined: 20-August 07

Re: Runtime error with dynamic memory allocation

Posted 13 October 2011 - 12:56 PM

The pointer which you're passing into your fillArray function is being copied, and the original pointer from your main function is not being updated.


Remember that a pointer is just a number, like an int. Just like passing any other kind of variable, if you want the pointer-variable which you pass to your function to be modified, then you need to make sure that you pass it by-reference

e.g. passing an int by-reference:
void foo(int & bar)

passing an int* by-reference:
void foo(int* & bar)



As a general suggestion - it's a bad idea to let functions allocate memory and to rely on the calling code to clean up that memory; you can often expect functions to be called in different places, and placing that kind of responsibility on every bit of code which calls a function is prone to mistakes being made and memory being leaked as a result.


You would do better to create and destroy the array within the same scope; this is for several reasons

- it doesn't matter whether you pass your pointer by-reference or not
- it also gives you the option to reuse your function for statically sized arrays and for vectors using &my_vector[0]
- a good rule of thumb for functions is one-function-one-purpose. Your function is called 'FillArray', so ideally it should just fill the array and not create it aswell.
int main()
{
    int* fred = new int[100];

    // TODO: Use fred


    delete [] fred;
} 

This post has been edited by Bench: 13 October 2011 - 01:04 PM

Was This Post Helpful? 3
  • +
  • -

#3 quim  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 18
  • View blog
  • Posts: 182
  • Joined: 11-December 05

Re: Runtime error with dynamic memory allocation

Posted 13 October 2011 - 01:40 PM

Thanks for the help but i still dont know the solution.
The excise from the book, (i have to use the same function header given)

Write a function called RandomArrayFill that inputs (i.e., takes a parameter) and integer array, and also that inputs (i.e takes a parameter) an integer, which contains the size of the array. The function is then to write a random number, in the range [0, 100], to each element of the array. The function declaration of this function should look like so:

void RandomArrayFill( int* array, int size );

[edited:]
Bench actually it does work if i use this
void foo(int* & bar)

as you suggested, passing pointer as a reference.
i wander if this was a mistake by the book or if there is another approach they wanted me to take??

This post has been edited by quim: 13 October 2011 - 01:49 PM

Was This Post Helpful? 0
  • +
  • -

#4 jimblumberg  Icon User is offline

  • member icon


Reputation: 4138
  • View blog
  • Posts: 12,875
  • Joined: 25-December 09

Re: Runtime error with dynamic memory allocation

Posted 13 October 2011 - 01:48 PM

You don't actually need to dynamically allocate the memory for the array in order to use this function. You can statically allocate the array and pass the size_of this array into the function as the size variable.

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

void fillArray(int* array, int size)
{
   for( int i = 0; i < size; i++)
   {
      array[i] = rand() % 100;
   }
}

int main()
{
   // seed the random number
   srand(time(0));

   int array[5];
   int size = 5;

   cout << "Filling the array with random numbers...\n";

   // filling array
   fillArray( array,size );
   cout << "\nArray = { ";
   for(int i = 0; i < size; i++ )
   {
      cout << array[i] << " ";
   }
   cout << "}\n";

   int array2[20];
   fillArray( array2,20 );
   cout << "\nArray = { ";
   for(int i = 0; i < size; i++ )
   {
      cout << array[i] << " ";
   }
   cout << "}\n";

   return(0);
}




Jim

This post has been edited by jimblumberg: 13 October 2011 - 01:48 PM

Was This Post Helpful? 0
  • +
  • -

#5 Salem_c  Icon User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 1706
  • View blog
  • Posts: 3,271
  • Joined: 30-May 10

Re: Runtime error with dynamic memory allocation

Posted 13 October 2011 - 11:47 PM

> i wander if this was a mistake by the book or if there is another approach they wanted me to take??
Books can have bugs just like anything else - probably more so. Having multiple sources of information helps when it comes to mistakes in the "literature".

As written, there is no way that void RandomArrayFill( int* array, int size ) can be responsible for allocating memory. It either needs the memory passed into it, as in jimblumberg's example, or the array needs to be some kind of out parameter, as in Bench's example.
Was This Post Helpful? 0
  • +
  • -

#6 Bigdukkha  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 1
  • Joined: 03-November 13

Re: Runtime error with dynamic memory allocation

Posted 03 November 2013 - 04:54 AM

There is one other way to do it. If you dynamically allocate memory it will work also.

#include<iostream>
#include<cstdlib>
#include<ctime>

using namespace std;

void randomArrayFill(int* array, int size);

int main()
{
	srand(time(0));
	
	cout << "Enter an array size: ";
	int size;
	cin >> size;
	int* array = new int[size];   
	randomArrayFill(array, size);

	for(int i = 0; i < size; i++)
	{
		cout << array[i] << " ";
	}

	system("pause");
	return 0;

}

void randomArrayFill(int* array, int size)
{
	for(int i = 0; i < size; i++)
	{
		array[i] = rand() % 101;
	}


}


Was This Post Helpful? -1
  • +
  • -

Page 1 of 1