Dynamic Memory Question

I'm reading a stereo .wav file into a buffer (allocated memory). My question is in regards to:

1. Checking if we've allocated the memory.
2. If so, let's delete it when we're done with it.

Simple enough, but I think I'm screwing the syntax up.

So I've declared a pointer to a pointer to an int:

int** buffer;

Then I tell the computer how much memory I'm going to need. I've inserted two integers where typically it would acquire this information from the .wav file format. The "2" represents the number of channels and the "100" represents the number of samples in the .wav file.

for (int = 0; i < 2; i++) buffers[i] = new int [100];

Finally lets run a loop that reads the samples data from the .wav into our memory:

1
2
3
for (int j = 0; j < 100; j++)
for (int i = 0; i < 2; i++)
	mmioRead(handle, (HPSTR)&buffers[i][j], sizeof(int));



All this works great, but I need to check if the buffer has been filled / created. Would the check be written like this:

1
2
3
4
if (!(buffer = new int)) // If it hasn't been filled...
{
//Do something here
}


Then to free up the memory again, something like this:

delete []buffer;

This should eliminate all the samples for both channels stored in memory...?

thanks
http://www.cplusplus.com/reference/vector/vector/

> I need to check if the buffer has been filled / created
If the allocation fails, it would throw an exception
Or you could use the nothrow version and check for NULL http://www.cplusplus.com/reference/new/nothrow/


> for (int = 0; i < 2; i++) buffers[i] = new int [100];
¿can you dereference `buffers'? (¿did you do something like buffers = new int*[2];?)
To allocate a 2d array and to validate you would do something like this (though I would use a stl container or smart pointer instead of raw pointer)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int **buffer = nullptr; //so that way you validate later

//allocate
buffer = new int*[rows];
for(int i = 0; i < rows; ++i)
{
    buffer[i] = new int[columns];
}


//to validate
if(buffer == nullptr)
{
    //it hasn't been allocated which would be very odd
}

//cleanup
for(int i = 0; i < rows; ++i)
{
    delete[] buffer[i];
}

delete[] buffer;


*had typo changed *int to int *
Last edited on
Topic archived. No new replies allowed.