What are “dangling links” and “general security error”?

I stumbled upon this over the network while I was studying stuff related to a memory leak.

int* Function() { int arrays[10]; /* Some code here */ return &(arrays[0]); } 

The author says that the above code fragment is valid, but the returned memory will be reused by the next function you call, so the same memory will be used for two purposes. This is called a “dangling link” and can lead to too intermittent errors or an old-fashioned “general security error”.

It would be great if someone can explain what the “dangling links” and “common protection error” are.

+7
source share
3 answers

I don’t know if these are official explanations, but I hope this gives a more appropriate meaning for this example:

substitution reference: the return statement returns a reference (pointer) to arrays. However, the memory is deleted (or maybe) after the function is closed, so there is a link that does not indicate the allocated memory, which is called a link to hang.

This can lead to a common security error. In general, a memory that is not allocated should not be written. If you try to do this, general protection may be raised by the operating system.

+2
source

This is not exactly a memory leak, since the allocated array will be automatically freed when the function returns. This is what is meant by a dangling link, you are returning a pointer to some memory that has been allocated on the stack. When the function returns, the allocated stack array is freed, so that the memory location can be overwritten with data for the next function call, so dereferencing the returned pointer will give the value undefined. This can cause a general security error, since the value of the pointer can change so that it points outside the valid address space; splitting such a pointer will result in a general security error.

+2
source

arrays is allocated on the stack when calling Function . Function returns the address of the structure allocated on the stack. When Function returns a stack pointer, it returns, but its data is still on the stack. When a previously released stack area is used by another function or area, this function will write local area data to the part of the stack that is still potentially accessible from the previously returned pointer.

This has 2 consequences:

  • If you try to access array data from outside the Function , that data is no longer reliable and will be (sooner or less) corrupted by a new distribution that overwrites this area of ​​the stack.
  • A new function allocated on the stack, if it does not initialize all its fields, may contain some dirty data

The result is undefined behavior and may also depend on your compilers and compilation options.

+1
source

All Articles