我有一个循环,每次都给我一个缓冲区,我想连接一个名为char
的{{1}}数组中的缓冲区然后我想将这些数据写入文件,但问题是我无法在没有seg-fault / core-dumped的情况下连接data
。
以下是代码(我也尝试char
代替new char[sizeof]
):
malloc
答案 0 :(得分:2)
您没有正确管理缓冲区,甚至没有关闭缓冲区。实际上,代码中存在很多错误。您sizeof()
次来电的每一次都是错误的。您在每次循环迭代时都会泄漏buffer
,tmp
和data
。您错误地使用了strcat()
。更糟糕的是,您正在使用字符串函数处理二进制音频数据?难怪为什么你的代码失败了。
尝试更像这样的东西:
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);
或更简单:
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);
但是,您将问题标记为C++
,即使您实际上并未使用C ++代码。处理这个问题的C ++方式看起来更像是这样:
#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();
或更简单:
#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();
或更简单:
#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();