Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different Unallocated Memory Behaviour Between Visual Studio Versions

i'm having a weird situation. i'm trying to implement a 10+ years old pci camera device SDK to my camera management software. Manifacturer no longer in business and i have no chance to get official help. So here I am, looking for some help to my ugly problem.

SDK comes with Visual Studio 6.0 samples. One of the include files has a structure ending with a one byte array like below;

typedef struct AVData {
    ...  
    BYTE audioVideoData[1];
}AVDATA, *PAVDATA;

But this single byte allocated byte array receives video frames and weird enough, it works fine with Visual Studio 6.0 version. If I try it with Visual Studio 2005/2008/2010, i start getting Memory Access Violation error messages which actully makes sense since it shouldn't be possible to allocate space to a fixed size array afterwards, no? But same code runs fine with VS 6.0?! It's probably caused by either compiler or c++ runtime differences but i'm not very experienced on this subject so it's hard to tell the certain reason for me.

I tried changing the size to an expected maximum number of bytes like below;

typedef struct AVData {
    ...  
    BYTE audioVideoData[20000];
}AVDATA, *PAVDATA;

This helped it get working but from time to time i get memory access violation problems when trying to destroy the decoder object of the library.

There is something definitely wrong with this. I don't have the source codes of the SDK, only the DLL, Lib and Header files. My questions are:

1) Is it really legal to allocate space to a fixed size array in Visual Studio 6.0 version?

2) Is there any possible way (a compiler option etc.) to make the same code work with newer VS versions / C++ runtimes?

3) Since my workaround of editing the header file works up to a point but still having problems, do you know any better way to get around of this problem?

like image 706
Emir Akaydın Avatar asked May 11 '12 13:05

Emir Akaydın


1 Answers

IIRC its an old trick to create a struct that is variable in size.

consider

struct {
  int len;
  char name[1];
} s;

the 'name' can now be of variable length if the appropriate allocation is done and it will be sequentially laid out in memory :

char* foo = "abc";
int len = strlen(foo);

struct s* p = malloc( sizeof(int) + len + 1 );

p->len = len;
strcpy(p->name, foo );

I think the above should work fine in newer versions of visual studio as well, maybe it is a matter of packing, have you done #pragma pack(1) to get structs on byte boundaries? I know that VS6 had that as default.

like image 178
AndersK Avatar answered Sep 21 '22 06:09

AndersK