Search code examples
c++exceptionvisual-c++stack-overflowportability

Stackoverflow exception occurring with C++ Codegear not with Visual C++


I have this scenario:

  • data management library written in Visual C++ but loaded and used inside C++ program written using Embarcadero CodeGear
  • library and functions loaded in program LoadLibrary and GetProcAddress

the issue is the following:

  • the library is ok in Visual C++ test environment
  • the program is crashing due to stackoverflow exception using the same calling function sequence with same parameters

simplified code for library:

struct TmRecordValue
{
    UINT8 RecordValue[128];
};
struct TmRecord{
    TmRecordValue RecordValues[2];
};
struct TmStruct
{
    UINT32 NumberOfRecords;
    TmRecord* Records;
};
void InitializeStruct(TmStruct* pStruct, int pNumberOfRecords)
{
    memset(pStruct, 0, sizeof(TmStruct));
    pStruct->NumberOfRecords = pNumberOfRecords;
    pStruct->Records = new TmRecord[pStruct->NumberOfRecords];
    memset(pStruct->Records, 0, sizeof(TmRecord) * pStruct->NumberOfRecords);
}
void AddRecordToStruct(TmStruct* pStruct, int pRecordIndex, char* pFirstValue, char* pSecondValue)
{
    strcpy_s(reinterpret_cast<char*>(pStruct->Records[pRecordIndex].RecordValues[0].RecordValue), 128, pFirstValue);
    strcpy_s(reinterpret_cast<char*>(pStruct->Records[pRecordIndex].RecordValues[1].RecordValue), 128, pSecondValue);
}

simplified code for program:

TmStruct *struct1 = new TmStruct();
int RecordsQuantity = 100000;
InitializeStruct(struct1, RecordsQuantity);
for (int i = 0; i < RecordsQuantity; i++)
{
    AddRecordToStruct(struct1, i, "first", "second");
}

Comments:

  • program running ok for RecordsQuantity = {10, 100, 1000, 10000} but crashing at 100000
  • the program is throwing stackoverflow exception on the AddRecordToStruct function
  • the program is throwing stackoverflow exception always on a fixed iteration (#62643)
  • I see no recursion behavior and no big stack variables (everything dinamically allocated I would say)
  • I would go with stack size increase but before I'd like to check the stack size of Visual C++ test environment against the stack size of the actual running program (but I don't know how to get current thread stack size)

Thanks in advance,


Solution

  • Check calling conventions. Make sure you use cdecl everywhere or stdcall everywhere.

    Because by symptoms it looks like Visual Studio library is cdecl but Embarcadero program assumes it to be stdcall, so no stack is deallocated neither by library, nor by caller.