Search code examples
c++libpq

c++ application is crashing when allocating a const char* const buffer


I'm having trouble with creating a buffer in my c++ application. I am being forced to create a const char* const* buffer so that I can use libpq's PQexecParams function.

PGresult *PQexecParams(PGconn *conn,
                    const char *command,
                    int nParams,
                    const Oid *paramTypes,
                    const char * const *paramValues,
                    const int *paramLengths,
                    const int *paramFormats,
                    int resultFormat);

Here is some code to reproduce the issue I'm getting STATUS_STACK_OVERFLOW exceptions when I allocate anything larger than 2.5MB for the buffer (for example running the program and specifying a size of 2621440.

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
        cout << "Buffer size Testing" << endl;
        cout << "==========================" << endl;
        int size;
        cout << "Size of buffer?" << endl;
        cout << "Size: ";
        cin >> size;
        try {
        const char * const *buffer[size];
        } catch (...){
                cout << "An error was encountered!" << endl;
                exit(1);
        }

        return 0;
}

What is the correct way to create a large buffer (2.5MB) for use with PQexecParams?


Solution

  • What your code is doing is allocation a big array of pointers on stack, which is why you get stack overflow exception.

    The proper way to allocate buffer on heap would be:

    char* buffer = new char[size]; // add consts where you need them
    

    However, I would follow suggestion from @BoBTFish and just use:

    std::vector<char> buffer(size);
    

    You can access the data buffer by either buffer.data() or by taking address of the first element: &buffer[0]. Vector will free allocated memory in its destructor.