重新分配返回 null?

发布于 2024-10-13 19:36:09 字数 847 浏览 4 评论 0原文

我用 malloc 分配了一些内存 - 大约 128 字节。

后来,我用大约 200 字节调用 realloc,但它返回 null!

如果我释放它,它会返回一个有效的指针,然后返回另一个malloc,但是我想使用realloc。

什么可以解释这种行为(我显然没有耗尽内存)?这是有效的行为吗?

代码位:

//class constructor
size = 0;

sizeAllocated = DEFAULT_BUFFER_SIZE; //64

data = (char*)malloc(sizeAllocated * sizeof(char)); //data is valid ptr now, I've checked it

data[0] = '\0';

//later on:
//append function
bool append(char** data, const char* str, size_t strLen) {
  if((size + strLen) >= sizeAllocated) {
     sizeAllocated += strLen + 1 + BUFFER_ALLOCATION_STEP;
     char* temp = realloc(*data, sizeAllocated * sizeof(char));
     if(temp)
        *data = temp;

     return( temp != NULL );

}

编辑:已修复。我超载了<<我的类的运算符,并让它返回 *this 而不是 void。不知怎的,这把一切都搞砸了!如果有人能解释为什么会发生这种情况,那就太好了!

I allocate some memory with malloc - about 128 bytes.

Later on, I call realloc with about 200 bytes, but it's returning null!

It returns a valid pointer if I do free, and then another malloc, however I would like to use realloc.

What could explain this behavior (I clearly am not running out of memory)? Is this valid behavior?

Code bits:

//class constructor
size = 0;

sizeAllocated = DEFAULT_BUFFER_SIZE; //64

data = (char*)malloc(sizeAllocated * sizeof(char)); //data is valid ptr now, I've checked it

data[0] = '\0';

//later on:
//append function
bool append(char** data, const char* str, size_t strLen) {
  if((size + strLen) >= sizeAllocated) {
     sizeAllocated += strLen + 1 + BUFFER_ALLOCATION_STEP;
     char* temp = realloc(*data, sizeAllocated * sizeof(char));
     if(temp)
        *data = temp;

     return( temp != NULL );

}

EDIT: fixed. I was overloading the << operator for my class, and had it return *this instead of void. Somehow this was screwing everything up! If anyone could explain why this happen, it would be nice!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱桃奶球 2024-10-20 19:36:09

由于以下评论已添加到问题中

data = (char*)realloc(data, (size_t)(sizeAllocated * sizeof(char)));

如果我用
具有相同值的常数,它
正确重新分配

现在我们可以弄清楚发生了什么。您用一个不具有相同值的常量替换了 sizeAllocation。出于调试目的,添加一条将输出 sizeAllocation 值的语句,您会感到惊讶。

Since the following comment was added to the question

data = (char*)realloc(data, (size_t)(sizeAllocated * sizeof(char)));

if I replace sizeAllocated with a
constant that is same value, it
reallocs correctly

Now we can figure out what happened. You replaced sizeAllocated with a constant that DID NOT have the same value. For debugging purposes, add a statement that will output the value of sizeAllocated and you will be surprised.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文