重新分配后使用原始指针? [英] Using original pointer after realloc?

查看:93
本文介绍了重新分配后使用原始指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读理查德·里斯(Richard Reese)的新书(2013年5月)在O'Reilly的书理解和使用C指针",并且对其中的某些代码有疑问,请参阅第87页.

I was reading Richard Reese's new (May 2013) O'Reilly book "Understanding and Using C Pointers", and I have a question about some code therein, on page 87.

if (++length > maximumLength) {
    char *newBuffer = realloc (buffer, maximumLength += sizeIncrement);

    if (newBuffer == NULL) {
        free (buffer);
        return NULL;
    }

    currentPosition = newBuffer + (currentPosition - buffer);
    buffer = newBuffer;
}

我希望变量的名称不言自明;如果需要上下文,我将进行编辑以提供完整的代码块,而不仅仅是此摘录.

I hope the names of the variables are self-explanatory; if context is needed, I will edit to provide the entire chunk of code and not just this excerpt.

我的问题是关于currentPosition = newBuffer + (currentPosition - buffer);行的.我对realloc()的理解是,当新分配成功时,将释放最初分配的内存.如果那是正确的,那么所讨论的行使用的是悬空指针,是吗?该表达式的RHS上的buffercurrentPosition都是指向已释放内存的指针.

My question is about the line currentPosition = newBuffer + (currentPosition - buffer);. My understanding of realloc() is that when the new allocation succeeds, the originally allocated memory is freed. If that is correct, then the line in question is using dangling pointers, innit? Both buffer and currentPosition on the RHS of that expression are pointers to memory that has been freed.

我的直觉是重写此代码,以避免通过使用length使用悬空的指针,毕竟该指针已经存在.我想将后两行替换为:

My instinct would be to rewrite this to avoid using the dangling pointers by using length, which after all is already around. I want to replace those last two lines with:

buffer = newBuffer;
currentPosition = buffer + length;

但是,假定编写的代码起作用了,因为两个指针仍然保留地址(尽管是垃圾),并且仍可以通过重新分配currentPosition的方式来计算这两个地址之间的偏移量.那么,我是否只是对此感到不自在呢?

However, presumably the code as written works because the two pointers still hold addresses (albeit of garbage), and the offset between those two addresses can still be calculated as a way of reassigning currentPosition. So am I being merely persnickety in feeling uneasy about this?

概括一下这个问题:指针悬空后,是否可以出于任何目的(例如计算偏移量)使用指针中包含的地址?谢谢.

To generalize the question: once a pointer is dangling, is it safe to use the address contained in the pointer for any purpose, such as calculating offsets? Thanks.

推荐答案

一旦指针悬空了,将指针中包含的地址用于任何目的(例如计算偏移量)是否安全?

once a pointer is dangling, is it safe to use the address contained in the pointer for any purpose, such as calculating offsets?

不,这不安全. free之后,指针值是一个无效地址,并且在不调用未定义行为的情况下,不能将无效地址用于指针算术.

No, it is not safe. After free the pointer value is an invalid address and an invalid address cannot be used for pointer arithmetic without invoking undefined behavior.

这篇关于重新分配后使用原始指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆