Похожие чаты

Can doing this result in any UB or segmentation fault

?

delete ptr2;
if (ptr1 == ptr2)
// some code

Because after deleting ptr2, it will be still holding its address.

31 ответов

16 просмотров

Should be fine

Well assuming delete ptr itself is not UB, it should be fine. Though i don't see the point behind comparing two pointers after one has been deleted

What type does ptr point to? Does it have a dtor?

It is UB according to the standard. Only comparison of pointers within an array (one past the end of the array) or a pointer to an object and a pointer just past the object or a nullptr can be compared with each other (unless you are using std::less). A deleted pointer is none of these though it may have been one of these before the deletion

Sahand-🏔️ Автор вопроса
Manav | avoid unnecessary messaging me
Well assuming delete ptr itself is not UB, it shou...

delete ptr2; if (ptr1 == ptr2) { ptr1 = nullptr; } I wanna make ptr1 nullptr, in case it points to a deleted block memory.

No this is Undefined behavior. You have to compare them before deletion

Sahand 🏔️
delete ptr2; if (ptr1 == ptr2) { ptr1 = nullpt...

Why do you have 2 pointers to the same thing?

Sahand-🏔️ Автор вопроса
Azadi
What type does ptr point to? Does it have a dtor?

It does have a dtor, but dtor is reliable in any situation. My dtor deallocates every allocated object. In case they are already deallocated, nothing new happens.

Thomas
depends on what they are pointing to

Irrespective of what they were initially pointing to, this is still Undefined Behavior as ptr2 becomes an invalid pointer after the delete expression. The standard says using an invalid pointer in any way other than assigning it a new value is UB

VD
Irrespective of what they were initially pointing ...

Compilers don't have the power to statically track lifetimes like that, so it will never actually become observable UB, it will always generate working code

Sahand-🏔️ Автор вопроса
Thomas
Why do you have 2 pointers to the same thing?

Assume I have an erase(). Well, for std erase(), it may take two iterators as arguments. But for my implementation, it takes two 'ints' as indices. erase() will first find the corresponding objects as the indices refer to (the second ptr to the obj), and also, I have already a pointer to the object (the first ptr to the obj).

Sahand-🏔️ Автор вопроса
Thomas
okay?

Now I have a remove() that deletes the second ptr. I need to make the first pointer to the object, if the second pointer (that is gonna be freed up) points to the same object the first one does.

Sahand 🏔️
Assume I have an erase(). Well, for std erase(), i...

You have an indice into a vec / array of... pointers?

Sahand-🏔️ Автор вопроса

basic.std.dynamic.deallocation If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value (4.10), the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. The effect of using an invalid pointer value (including passing it to a deallocation function) is undefined.

He's not using an invalid pointer *value*

Thomas
He's not using an invalid pointer *value*

When comparing two pointers, you are indeed using the value. Value here refers to the address the pointer points to

Thomas
Why would that be UB?

Because the standard says so

VD
basic.std.dynamic.deallocation If the argument gi...

It is not Undefined Behavior but Implementation defined behavior

VD
Errm, I just quoted the standard.

You quoted an old version of the standard. Here is the latest: If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value (4.10), the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.

VD
Errm, I just quoted the standard.

What link do you quote from? This is the version I visit occasionally: https://eel.is/c++draft/basic.stc.dynamic

Azadi
What link do you quote from? This is the version I...

I have the draft copies downloaded as PDF. I quoted from the wrong standard as pointed out. I must remember to sort the draft copies by date before opening up the one on top.

VD
I have the draft copies downloaded as PDF. I quote...

I think if there was such a statement in standard it'd surely exist in that up to date version I linked. Of course I found that statement on isocpp but with a old data, like 2012 or so. So I guess standard may not have any statement regarding that issue. But not sure yet.

Azadi
I think if there was such a statement in standard ...

You are referring to my statement or the one posted by Madhu? The one that Madhu posted is on CPPReference even. https://en.cppreference.com/w/cpp/language/pointer Check out the section on Pointer (2nd paragraph there) Since C++17, this piece on invalid pointers has been moved to another section of the standard. So don't search for it in deallocation

VD
You are referring to my statement or the one poste...

I was looking for that statement generally, ofc on the standard.

Azadi
I was looking for that statement generally, ofc on...

https://eel is/c++draft/basic.stc#general

Похожие вопросы

Обсуждают сегодня

At which price point will BCH, an ASIC mined coin, be succeptible to reorg attacks because of low hashrate? $10? $1? $0.1? $0.01?
Kishniev
18
А кто-то пробовал, уезжая из Эстонии получить э-рез и продолжить вести предпринимательскую деятельность внутри Эстонии, используя свой OÜ?
Lalalashechki Lalala
62
зачем же переименовывать ? чтобы кол-во участников возросло или вдруг IBM от этого снова на свифте начнет кодить ? Я не понимаю что страшного в том что свифт гавно, если это т...
Oleh Nerzh
10
Is Kadena onto something special? No one really knows. Good luck!
Bright Uncle Stephen EqualBet
40
Гайз, кто-нибудь пробовал запустить probe-rs под камень, которого нет в probe-rs? Мб есть какой-нибудь пример у кого... Через target-gen попробовал сгенерировать chip-descript...
Максим Смирнов
2
я не магистр хаскеля, но разве не может лейзи тип конвертнуться в не-лейзи запросив вычисление содержимого прям при инициализации?
deadgnom32 λ madao
100
Hello VIC team, I had previously used the “wallet.tomochain.com” with a ledger connection. Unfortunately, the site is no longer accessible and the ledger account is not visibl...
carpe noctem
7
здравствуйте. совершаю вот такую вещь: strcpy(line, (char)current_number); где current number — неподписанный шорт, line — массив чаров. ругань следующая: main.c:29:30: error...
Roberto's Ширгозиев
13
@MrMiscipitlick А можешь макрос написать, который будет вычислять смещение относительно переданных меток? Просто .label1-.label2, и вернуть значение.
КТ315
35
А еще в перле можно уже @arr1 + @arr2?
Sergei Zhmylove
53
Карта сайта