Different behaviour of new and malloc

Ali Çehreli acehreli at yahoo.com
Sat Apr 13 14:51:35 PDT 2013


On 04/13/2013 02:22 PM, Namespace wrote:

 > I have a opengl texture and I want to copy the pixel. I store the
 > original pixel in an ubyte pointer and allocate new pixel memory with:
 > ubyte[] newPixel = new ubyte[this.width * this.height * this.depth];

Make sure that you really do not need to multiply that byte count with 
the .sizeof property of the actual value. But I guess it is fine because 
the elements are ubyte and ubyte.sizeof is 1.

 > and copy the pixel with
 > newPixel[] = *orgPixel;

That copies the first element of orgPixel to every element of newPixel. 
Probably not something that you want.

 > or
 > memcpy(&newPixel[0], orgPixel, this.width * this.height * this.deph);

That is different. Now you are copying all of the elements at orgPixel.

 > Both compiles without errors or warnings.
 > But if I want to store the newPixel in a new Texture, I see only black,
 > no matter what method I use.

Are you sure that the memcpy method doesn't work?

 > But if I change my allocation to
 > ubyte* newPixel = cast(ubyte*) GC.malloc(this.width * this.height *
 > this.deph * ubyte.sizeof);
 > and copy then with
 > memcpy(&newPixel[0], orgPixel, this.width * this.height * this.deph);
 >
 > it works fine and I see the copied texture.
 >
 > My question is: why? What is the difference between both ways of
 > allocations?

Can you show two small programs that behaves differently. :)

Ali



More information about the Digitalmars-d-learn mailing list