[Solved] Dynamic Char Allocation [closed]


You are not managing your buffers correctly, not even close. In fact, there are a LOT of mistakes in your code. Every one of your sizeof() calls is wrong. You are leaking buffer, tmp, and data on every loop iteration. You are using strcat() incorrectly. And worse, you are processing binary audio data using string functions? No wonder why your code is failing.

Try something more like this instead:

char* getBuffer(int *bufsize)
{
    ...
    *bufsize = ...; // <-- number of bytes being returned
    return ... ; // <-- malloc()'ed pointer to actual bytes
}

...

char *data = NULL;
int datasize = 0;
int allocsize = 0;

char *buffer;
int bufsize;

for (loops = 100; loops > 0; loops--) {
    buffer = getBuffer(&bufsize);

    if ((datasize + bufsize) > allocsize)
    {
        // round new size up to next 1K boundary
        int tmpsize = (datasize + bufsize + 1023) & ~1023;

        char *tmp = (char*) realloc(data, tmpsize);
        if (!tmp) {
            free(buffer);
            break;
        }

        data = tmp;
        allocsize = tmpsize;
    }

    memcpy(data + datasize, buffer, bufsize);
    datasize += bufsize;

    free(buffer);
}

FILE *f = fopen(..., "wb");
fwrite(data, datasize, 1, f);
fclose(f);

free(data);

Or simpler:

char *buffer;
int bufsize;

FILE *f = fopen(..., "wb");

for (loops = 100; loops > 0; loops--) {
    buffer = getBuffer(&bufsize);
    if (fwrite(buffer, bufsize, 1, f) != 1) {
        free(buffer);
        break;
    }
    free(buffer);
}

fclose(f);

However, you tagged your question as C++, even though you are not actually using C++ code. The C++ way to handle this would look more like this instead:

#include <vector>
#include <string>
#include <fstream>

void getBuffer(std::vector<char> &buffer)
{
    ...
    buffer.resize(...); // <-- number of bytes
    // fill buffer with bytes as needed...
}

...

std::string data;

for (loops = 100; loops > 0; loops--) {
    std::vector<char> buffer;
    getBuffer(buffer);
    data.append(buffer.data(), buffer.size());
}

std::ofstream f(..., std::ios_base::binary);
f.write(data.c_str(), data.size());
f.close();

Or simpler:

#include <string>
#include <fstream>

void appendBuffer(std::string &buffer)
{
    ...
    buffer.append(...); // <-- append bytes
}

...

std::string data;

for (loops = 100; loops > 0; loops--) {
    appendBuffer(data);
}

std::ofstream f(..., std::ios_base::binary);
f.write(data.c_str(), data.size());
f.close();

Or simpler:

#include <fstream>

bool outputBuffer(std::ostream &out)
{
    ...
    return out.write(...); // <-- write bytes
}

...

std::ofstream f(..., std::ios_base::binary);

for (loops = 100; loops > 0; loops--) {
    if (!outputBuffer(f)) break;
}

f.close();

1

solved Dynamic Char Allocation [closed]