All Questions

818
votes
20answers
238732 views

Can a local variable's memory be accessed outside its scope?

I have the following code. int * foo() { int a = 5; return &a; } int main() { int* p = foo(); cout << *p; *p = 8; cout << *p; } And the code is just running...
31
votes
5answers
36042 views

What is a dangling pointer

I know this is pretty common question, but still new for me! I don't understand concept of dangling pointer, was googling around, and writing test methods to find one ... I just wonder is this a dang...
166
votes
5answers
43949 views

What is the difference between a weak reference and an unowned reference?

Swift has: Strong References Weak References Unowned References How is an unowned reference different from a weak reference? When is it safe to use an unowned reference? Are unowned references a...
68
votes
3answers
2174 views

Is it legal to compare dangling pointers?

Is it legal to compare dangling pointers? int *p, *q; { int a; p = &a; } { int b; q = &b; } std::cout << (p == q) << '\n'; Note how both p and q point to objects...
3
votes
2answers
3497 views

Sieve of Eratosthenes algorithm in C

Okay, so this function I created uses the Sieve of Eratosthenes algorithm to compute all the primes <= n. This function stores the prime numbers and the count of primes in the parameters. When th...
1
votes
3answers
615 views

realloc() dangling pointers and undefined behavior

When you free memory, what happens to pointers that point into that memory? Do they become invalid immediately? What happens if they later become valid again? Certainly, the usual case of a pointer...
1
votes
7answers
3376 views

Dangling Pointer in C

I wrote a program in C having dangling pointer. #include<stdio.h> int *func(void) { int num; num = 100; return &num; } int func1(void) { int x,y,z; scanf("%d %d",&...
19
votes
3answers
1267 views

Detect dangling references to temporary

Clang 3.9 extremely reuses memory used by temporaries. This code is UB (simplified code): template <class T> class my_optional { public: bool has{ false }; T value; const T& g...
4
votes
5answers
1330 views

What's the difference between delete-ing a pointer and setting it to nullptr?

Is saying delete pointer and pointer = nullptr the same? Probably not, but does the latter free up memory? What about delete pointer; pointer = nullptr / pointer = nullptr; delete pointer? Why not use...
4
votes
7answers
718 views

Safe in C# not in C++, simple return of pointer / reference

C++ code: person* NewPerson(void) { person p; /* ... */ return &p; //return pointer to person. } C# code: person NewPerson() { return new person(); //return reference to person. } If...

Previous Next