logo
down
shadow

Dangling pointer example confusion


Dangling pointer example confusion

By : Masho
Date : November 22 2020, 09:00 AM
may help you . Why isn't the following example correct? Why doesn't it demonstrate a dangling pointer? My teacher said it doesn't show the dangling pointer. in advance! , To cite Wikipedia:
code :
{
   char *ptr = NULL;

   {
       char c;
       ptr = &c;
   } 
     // c falls out of scope 
     // ptr is now a dangling pointer 
}
int *p = malloc(sizeof(int));
*p = 9;
free(p); // now p is dangling


Share : facebook icon twitter icon
Why is assigning 0 to a pointer a solution to a dangling pointer?

Why is assigning 0 to a pointer a solution to a dangling pointer?


By : Kirkhammetz
Date : March 29 2020, 07:55 AM
seems to work fine The essential problem this solves is that not all CPU's implement the same sorts of memory dereference semantics. In some cases, it's not possible to make dereferencing an address after it has been free() into anything that looks like an error. This is especially true on embedded processors. In other cases, allocators may be very lazy about returning freed memory to the host operating system, for performance reasons.
Fundamentally, dereferencing such a pointer could lead to actually seeing the freed region, seeing a zeroed out region, seeing memory that has been returned by a subsequent allocation, or causing a cpu exception. Since such an eventuality is completely reasonable, c++ has assigned this condition as "undefined behavior".
C++ dangling pointer/deep copy/shallow copy confusion

C++ dangling pointer/deep copy/shallow copy confusion


By : Casey Pritts
Date : March 29 2020, 07:55 AM
it should still fix some issue The problem is, you are passing by value.
So your parameter have their own addresses which are differnet from your pointers. What you want is passing by pointer or refernce:
code :
// by pointer
void printAdressesPtr(int* p1, int* p2) {
    std::cout << "p1 - ptr: " << p1 << " - value: " << *p1 << std::endl;
    std::cout << "p2 - ptr: " << p2 << " - value: " << *p2 << std::endl;

    std::cout << "p1 - ptr ref: " << &p1 << std::endl;
    std::cout << "p2 - ptr ref: " << &p2 << std::endl;
}

// by reference
void printAdressesRef(int& r1, int& r2) {
    std::cout << "r1 - ref: " << &r1 << " - value: " << r1 << std::endl;
    std::cout << "r2 - ref: " << &r2 << " - value: " << r2 << std::endl;
}

// by value (copy)
void printAdressesVal(int v1, int v2) {
    std::cout << "v1 - ref: " << &v1 << " - value: " << v1 << std::endl;
    std::cout << "v2 - ref: " << &v2 << " - value: " << v2 << std::endl;
}

int main() {
    int* ptr1 = new int(123);
    int* ptr2 = ptr1;

    printAdressesPtr(ptr1, ptr2);
    printAdressesRef(*ptr1, *ptr2);  
    printAdressesVal(*ptr1, *ptr2);

    return 0;
}
class Player {
public:
  std::string name;
  std::string countryName;
  std::string gameName;
  int         age;

  Player() {}

  Player(std::string const& n, std::string const& c, std::string const& g, int a)
    : name(n), countryName(c), gameName(g), age(a) {} // this are deep copies

  // copy constructor
  Player(Player const& cpy)
    : name(cpy.name)
    , countryName(cpy.countryName)
    , gameName(cpy.gameName)
    , age(cpy.age) {} // this are deep copies
};
class Player {
public:
  char* name;
  char* countryName;

  Player()
    : name(nullptr), countryName(nullptr) {}

  Player(char* n, char* c) {
    // deep copy. name has his own memmory allocated and the value is copied 
    // from n to name
    name = new char[strlen(n) + 1]; 
    strcpy(name, n);

    // shallow copy. contryName and c have the same address of the value.
    // changing contryName of P2 is also changing contryName of P1. also there is no
    // guarantee that enough space is allocated.
    contryName = c;
  }


  // copy constructor
  Player(Player const& cpy) {
    // this is a deep copy. name has his own memmory allocated and the value is copied
    // from n to name
    name = new char[strlen(cpy.name) + 1]; 
    strcpy(name, cpy.name);

    // shallow copy. contryName and c have the same address of the value.
    // changing contryName of P2 is also changing contryName of P1. Also there is no
    // guarantee that enough space is allocated...
    contryName = c;
  }

  ~Player() {
    if(name != nullptr)
      delete name;
    name = 0;

    // this will also delete contryName of P1. access from P1 is undefined behavior...
    if(contryName != nullptr)
      delete[] contryName;
    contryName = 0;
  }
};
Getting a dangling pointer by returning a pointer from a local C-style array

Getting a dangling pointer by returning a pointer from a local C-style array


By : Diego
Date : March 29 2020, 07:55 AM
Hope this helps I am a bit confused by the following code: , No, it's not UB.
This:
code :
const char* f()
{
    const char* arr[]={"test"};
    return arr[0];
}
const char* f()
{
    const char* arr0 = "test";
    return arr0;
}
const char* f()
{
    return "test";
}
const char* f() {
    const char arr[] = "test"; // local array of char, not array of char const*
    return arr;
}
Dangling pointer in case of integer pointer vs char pointers

Dangling pointer in case of integer pointer vs char pointers


By : Gregory Williamson
Date : March 29 2020, 07:55 AM
seems to work fine As you know, returning a pointer to a local variable is not guaranteed to work. So neither your get_int_ptr nor your get_char_ptr function can be expected to work.
(Foreshadowing the answer: "not guaranteed to work" is not quite the same as "guaranteed not to work".)
Do we get a dangling pointer by copying a dangling pointer?

Do we get a dangling pointer by copying a dangling pointer?


By : teyss
Date : September 22 2020, 06:00 AM
I wish this help you Yes, you do. As pointed out in the comments on your question, you cannot "check it" by using printf. From the moment that the function stack is popped, you're dealing with undefined behavior.
Use valgrind to run your program, and it will point out any read/write errors. Those may not cause your program to fail every time, but should be taken care of nonetheless. I'm sure your dangling pointer will show up in there, and valgrind will be kind enough to show you the full trace of where each error occurs.
Related Posts Related Posts :
  • Expected ' ' before '=' token in struct definition
  • How to implement a MATLAB lowpass filter in C
  • Convert hexidecimal char array to u8 array in C
  • Delete function in Binary Tree in C
  • Why (int)((unsigned int)((int)v)?
  • Creating a matrix in a structure
  • C Recursion runtime error
  • C: pointer to 2d array
  • How to free a pointer in a structure array?
  • gcc -O optimization: Help me understand the effect
  • Errors on code (state machine)
  • Does node equals node on a struct initializes the rest of the struct attributes?
  • C program to copy one string into other string without using library functions
  • Macro representing a pin on a microchip
  • C code workks in Mac (Darwin 13.4), but not in Linux (2.6.32)
  • How do I read this complex C declaration?
  • Reading a file with scanf and a do while loop
  • why is the recursion used in finding the factorial of a number?
  • Inverting array elements (bitwise) doesn't work
  • git blame-like annotation of source files with gcov
  • Error using pthread on Windows with Mingw
  • How to create a static library with a Makefile from C source code
  • Why are there two different ways of initializing a pointer in C
  • Program runs too slowly with large input - C
  • Why is this program running when input is 1?
  • Malloc() doesn't work + char array clear
  • Reading debug registers on linux
  • Socket Programming - Server content written to Client (write())
  • Incrementing a string in C
  • what does a[0] = addr & 0xff?
  • unexpected EOF while looking for matching `'' while using execve()
  • What's the purpose of stack pointer alignment in the prologue of main()
  • Time from startup in linux kernel
  • UNIX socket connection refused
  • How to programmatically set IP address on Windows 7 using C
  • programming a gpu without using any library like cuda or opencl?
  • C "printf" Different output in Linux and Mac
  • Bit rearrangement/manipulation in C
  • How to find occurences of a digit with 4 in it within 50?
  • Read string separated by comma
  • how to optimize the C code, when m is too big, it can't operation
  • GCC Error Infinite While Loop
  • Row-major vs Column-major confusion
  • Parsing memory mapped file C
  • going out of bounds in array of structs in C
  • fprintf in do while loop wrote only one line in file C
  • Reading and Writing to Files in C
  • Changable amount of scanned numbers per line (scanf)
  • Turtle drawing fractal with openGl
  • c database program using structs
  • How to handle 3 way send() and recv() in BSD socket using C
  • 2D Array: Alphabetical Sorting in C
  • setting the size of array
  • How Do I Fix This Sorted Linked List Insertion?
  • windows mingw asterisk '*' passing by argv[1] to string
  • C - values in array overriden after leaving while loop
  • C String cropping runtime error
  • Adding custom extension to PKCS#10 request using OpenSSL (programatically)
  • Dynamically allocate enough memory on client and server receive part
  • How can I store these numbers in C?
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co