Похожие чаты

Hey guys When returning a ptr from a function, in some

cases, the ptr MUST be static or allocated on the heap (without getting deleted too early) to successfully return and use it. Conversely, there are some cases that compiler doesn't care if it is static or non static, or even it is allocated on the stack or not.
This simply has made me baffled ...
Can you clear it up to me ?
When can the ptr live on the stack and when cannot ?

Below I have provided some examples of my problem.

https://pastebin.ubuntu.com/p/NMtsTXTvJc/

https://pastebin.ubuntu.com/p/9FxwpDtT7D/

23 ответов

15 просмотров

The first one by the first link is not OK though, it's UB as you keep reference to a local variable after its lifetime has ended

By the second link you use an uninitialized pointer, which is also UB (the value of the pointer is some random garbage from the memory, so it doesn't point to any valid vector)

Sahand-🏔️ Автор вопроса
Pavel
The first one by the first link is not OK though, ...

Then why isn't my program terminated/crashed ? I need to know when my program gets terminated and when it does not

Sahand-🏔️ Автор вопроса
Pavel
By the second link you use an uninitialized pointe...

But pointer CAN be initialized later, can't it ?? I have two instances which pass an address of a vector to the ctor, and then the ctor initializes the pointer .. I don't understand why it is UB

It's simple, consider the lifetime of the variable when you return a pointer to it.

Sahand-🏔️ Автор вопроса
Sahand 🏔️
But pointer CAN be initialized later, can't it ?? ...

@gameraccoon how bout this one ? I mean I initialized the pointer later on, I don't understand why this is called ub too

Sahand 🏔️
@gameraccoon how bout this one ? I mean I initiali...

Just to make sure, you are referring to your second link from before? I may have misread something there I can double-check

Sahand-🏔️ Автор вопроса
Pavel
Just to make sure, you are referring to your secon...

Yeah the second one. The one that has a 2d vector which is of a pointer. It is in private part of my clas

Sahand 🏔️
Yeah the second one. The one that has a 2d vector...

On line 57 you initialize it with the default constructor, which leaves the pointer uninitialized, then on line 59 you call resize on an uninitialized pointer, at this moment your program enters UB and what happens later doesn't really matter anymore as it is already invalid

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

Did you read this (https://t.me/thedevs_c/246336) from the other day? Do not return a local pointer/reference.

In the first link, num and x[] are local objects, so you should not return a pointer to them.

In the second link, on line 59, you're resizing a std::vector which has not any size yet through a pointer! That's why you face a related problem. It's not UB. Here's simpler version of the project without pointers though. https://pastebin.ubuntu.com/p/CPv7MQDvgm/

Azadi
In the second link, on line 59, you're resizing a ...

It is OK to call resize on an empty vector The problem is that the vector didn't exist at that point (and it is UB after all)

Pavel
It is OK to call resize on an empty vector The pro...

Yes, that pointer in not initialized as you pointed out. But I believe it's not UB. The segmentation fault relates to accessing part of memory which isn't at hand. So the behavior is well defined and it's an error. Most of the time, the compiler won't show any error for UB. Sometimes there might be warnings though (if the flags are set)

Sahand-🏔️ Автор вопроса
Azadi
In the second link, on line 59, you're resizing a ...

Just a small point here: I don't know why people discourage me from using pointers here, just like you did in your code. Using pointers is not bad practice is it ? Like in Qt Widgets pointers are everywhere... And I personally used it in my code just as a practice, in order to get the hang of ptr and get comfortable with'em.

Sahand 🏔️
Just a small point here: I don't know why people d...

The reason people discourage you (or anyone) from using pointers is the issues with them. Up to now, you faces two of them: UB and Segmentation Fault. They're powerful but it needs much effort and cautious to use. So some pieces of advice I've learnt are: - Do not use pointers unless you need and know how to use them - Do not use raw pointers; use smart ones. The case with QtWidget is different from one aspect: It offers a parent-child relationship which properly deallocate heap memory allocated by the pointers at program termination automatically, preventing memory leak.

Sahand-🏔️ Автор вопроса
Azadi
The reason people discourage you (or anyone) from ...

Please don't put the blame on pointers for the segmentation fault error 🙃 I should've paid much more attention to what I was writing. It was simply a blunder. I was attempting to allocate some space for a 2D vector whose type was pointer, while it was NOT even initialized !! So clearly I'll see a lot of error then. It was actually my fault 😅 as Pavel found my the bug. But the thing is, I may not know when to use ptr. Perhaps it should he used wisely and not passing around pointers everywhere. It'll get us into much trouble then.....

This is the wrong way to think about it tbh

Sahand-🏔️ Автор вопроса
Thomas
This is the wrong way to think about it tbh

Yeah I assumed that some days the compiler feels like complaining about undefined behaviors and stops my program entirely, and some days it does not (while it gives the output). I thought it was optional or something..

Azadi
Yes, that pointer in not initialized as you pointe...

It is UB though "Creation" section here https://en.cppreference.com/book/pointers As I described above you are not guaranteed to get a segmentation fault here, this code can result in anything, probably wise is much more likely that: - the compiler will not add additional checks (the compiler can do that even in release builds, but it usually needs to be configured) - the garbage value that was in the memory that was used for the pointer does not point to any memory within your program - your OS shields applications from accessing wrong memory (and you have an OS in the first place). - the compiler can't determine that you are going to dereference an initialized pointer and will not throw away this code as "never executed in a valid program" If any of these are false you can get a different behavior than segmentation fault

Sahand 🏔️
Just a small point here: I don't know why people d...

People discourage usage of raw pointers because of the amount of errors commonly associated with manual memory management, pointer math and other aspects of pointer usage. So while being a very useful tool, they are proven to deal a good amount of damage as well according to statistics. So while you're working on study projects it is good to use them because in real life projects there are going to be a lot of them. But in the real projects (especially, if the failures in these projects can lead to losing money or worse) I would encourage to use smart pointers or avoid pointers when possible. All people make mistakes, there's no way from that, what we can do is use better tools that will catch these mistakes before going to production and failing in real conditions. Raw pointers usage is proven to be very bad at being analyzable in this sense

Sahand-🏔️ Автор вопроса
Pavel
People discourage usage of raw pointers because of...

Agreed. Everything makes sense. C++ can be less difficult if we use smart pointers instead raw ones.

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

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

А кто-то пробовал, уезжая из Эстонии получить э-рез и продолжить вести предпринимательскую деятельность внутри Эстонии, используя свой OÜ?
Lalalashechki Lalala
62
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
Is Kadena onto something special? No one really knows. Good luck!
Bright Uncle Stephen EqualBet
40
зачем же переименовывать ? чтобы кол-во участников возросло или вдруг IBM от этого снова на свифте начнет кодить ? Я не понимаю что страшного в том что свифт гавно, если это т...
Oleh Nerzh
10
Гайз, кто-нибудь пробовал запустить probe-rs под камень, которого нет в probe-rs? Мб есть какой-нибудь пример у кого... Через target-gen попробовал сгенерировать chip-descript...
Максим Смирнов
2
я не магистр хаскеля, но разве не может лейзи тип конвертнуться в не-лейзи запросив вычисление содержимого прям при инициализации?
deadgnom32 λ madao
100
здравствуйте. совершаю вот такую вещь: strcpy(line, (char)current_number); где current number — неподписанный шорт, line — массив чаров. ругань следующая: main.c:29:30: error...
Roberto's Ширгозиев
13
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
@MrMiscipitlick А можешь макрос написать, который будет вычислять смещение относительно переданных меток? Просто .label1-.label2, и вернуть значение.
КТ315
35
А еще в перле можно уже @arr1 + @arr2?
Sergei Zhmylove
53
Карта сайта