it seems that my C++ skills are super rusted these days... i have the simplyfied problem code stated underneath:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <stdio.h>
int main()
{
int *bannerPixelBuffer = newint[1024];
for(int y = 0;y < 1024; y++ )
{
*(bannerPixelBuffer++) = 1024;
//bannerPixelBuffer[y] = 1024; //This works...but is first of al slow as hell, second of al...people did this before me...what am i missing here:s
}
delete bannerPixelBuffer; ///EEEEH error...
// neither does this help delete []bannerPixelBuffer;
return 0;
}
Wel my code works great...(i think) until it hits the 'delete'.
I get "debug assertion failed" from visual studio...yep you guessed it...an invalid pointer...now how do i delete this thing from my memory!!:-D
Also, compiling the following program with gcc -O3 -S, the resultant assembler code for fn1() and fn2()
is absolutely identical so there cannot be a speed difference. Perhaps you are compiling without
optimizations?
Anyhow...i found my stupid mistake:-(
The solution was actually very easy:p
You see the pointer index should be 0 when deleting (or so goes my theory)...that's why i made a copy of my allocated memory (starting at index 0) and in the end i deleted my copy, wich is the same as my bannerpixelbuffer memory...
1 2 3 4 5 6 7 8 9 10 11
int *bannerPixelBuffer = newint[1024];
int *temp = bannerPixelBuffer;
for(int y = 0;y < 1024; y++ )
{
*(bannerPixelBuffer++) = y;
}
delete temp;
return 0;
I can't thank you guys enough for the quick respons!:-D
Could you belief that it took me 8 hours to realize my mistake:s
With that code posted above, would the delete temp; line really de-allocate all the memory allocated to bannerPixelBuffer? I would think it would only delete the space contained by one int variable, since temp == temp[0].
Someone correct me if I'm wrong, I can't run valgrind on this to support my conclusion.
I think it is usually best to use:
delete[] variable;, where variable is the array dynamically allocated.