views:

374

answers:

1

Hi

I am trying to convert an IStream to HBITMAP using the GDI+ Bitmap class. The IStream object is being populated by using data from a web service. I am reading the data in parts and appending it to an object to be used later with the Bitmap class.

Here is the relevant part of the code

  char data1[] = "";
  int offset = 0;

  LPTSTR pszString = NULL;
  LPSTREAM lpStream = NULL;

  CreateStreamOnHGlobal(NULL, TRUE, &lpStream);
  StreamStringCopy ((LPSTREAM)lpStream, (LPCTSTR)"");
  while(of->pread(&data1,1023,offset) > 0){
   LPCTSTR tempStr = data1;
   StreamStringCat ((LPSTREAM)lpStream, tempStr);
   offset = offset + strlen(data1); 
  }
  Bitmap bm(lpStream,FALSE);
  bm.GetHBITMAP(Color.Black, &ret);

StreamStringCat appends the string to the LPSTREAM object so I can get a single LPSTREAM object.

The loop runs fine only the first time. When the while loop is entered again, the &data1 gives an Access violation exception.

Can someone please tell me how I should resolve this issue. Thanks.

+1  A: 

First, be careful with string literals. String literals like "" are of type const char*, so you cannot write to them. I'm not entirely sure whether your construct char data1[] = "" makes it writable, but even if so, you have only memory for 2 characters there, while you (I suppose) try to read 1023 bytes into the location of data1. Try this:

char* data1 = static_cast<char*> (std::malloc (1024 * sizeof (char));

...

std::free (data1);

// or try this
char data1 [1024] = { 0 }; // Gives you 1024 bytes to write to on the stack

This allocates some memory, which can be written to. I guess after the first run, you've overwritten some memory, which leads to the access violation in the next run.

Anteru