1

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?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Kons
  • 73
  • 1
  • 7
  • [`std::vector buffer(size);`](http://en.cppreference.com/w/cpp/container/vector) The use `buffer.data()` as the pointer. And note that since yours is a buffer of `const char`, how do you ever expect to be able to store the values? – BoBTFish Dec 09 '15 at 14:17
  • 1
    Don't add tags for unrelated languages. – too honest for this site Dec 09 '15 at 14:18
  • Possible duplicate of [Seg Fault when initializing array](http://stackoverflow.com/questions/3815232/seg-fault-when-initializing-array) – Klas Lindbäck Dec 09 '15 at 14:18

1 Answers1

2

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.

ovk
  • 2,318
  • 1
  • 23
  • 30