You can use valgrind
to debug it.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *x = malloc(100);
free(x);
free(x);
return 0;
}
[sand@PS-CNTOS-64-S11 testbox]$ vim t1.c
[sand@PS-CNTOS-64-S11 testbox]$ cc -g t1.c -o t1
[sand@PS-CNTOS-64-S11 testbox]$ ./t1
*** glibc detected *** ./t1: double free or corruption (top): 0x00000000058f7010 ***
======= Backtrace: =========
/lib64/libc.so.6[0x3a3127245f]
/lib64/libc.so.6(cfree+0x4b)[0x3a312728bb]
./t1[0x400500]
/lib64/libc.so.6(__libc_start_main+0xf4)[0x3a3121d994]
./t1[0x400429]
======= Memory map: ========
00400000-00401000 r-xp 00000000 68:02 30246184 /home/sand/testbox/t1
00600000-00601000 rw-p 00000000 68:02 30246184 /home/sand/testbox/t1
058f7000-05918000 rw-p 058f7000 00:00 0 [heap]
3a30e00000-3a30e1c000 r-xp 00000000 68:03 5308733 /lib64/ld-2.5.so
3a3101b000-3a3101c000 r--p 0001b000 68:03 5308733 /lib64/ld-2.5.so
3a3101c000-3a3101d000 rw-p 0001c000 68:03 5308733 /lib64/ld-2.5.so
3a31200000-3a3134e000 r-xp 00000000 68:03 5310248 /lib64/libc-2.5.so
3a3134e000-3a3154e000 ---p 0014e000 68:03 5310248 /lib64/libc-2.5.so
3a3154e000-3a31552000 r--p 0014e000 68:03 5310248 /lib64/libc-2.5.so
3a31552000-3a31553000 rw-p 00152000 68:03 5310248 /lib64/libc-2.5.so
3a31553000-3a31558000 rw-p 3a31553000 00:00 0
3a41c00000-3a41c0d000 r-xp 00000000 68:03 5310264 /lib64/libgcc_s-4.1.2-20080825.so.1
3a41c0d000-3a41e0d000 ---p 0000d000 68:03 5310264 /lib64/libgcc_s-4.1.2-20080825.so.1
3a41e0d000-3a41e0e000 rw-p 0000d000 68:03 5310264 /lib64/libgcc_s-4.1.2-20080825.so.1
2b1912300000-2b1912302000 rw-p 2b1912300000 00:00 0
2b191231c000-2b191231d000 rw-p 2b191231c000 00:00 0
7ffffe214000-7ffffe229000 rw-p 7ffffffe9000 00:00 0 [stack]
7ffffe2b0000-7ffffe2b4000 r-xp 7ffffe2b0000 00:00 0 [vdso]
ffffffffff600000-ffffffffffe00000 ---p 00000000 00:00 0 [vsyscall]
Aborted
[sand@PS-CNTOS-64-S11 testbox]$
[sand@PS-CNTOS-64-S11 testbox]$ vim t1.c
[sand@PS-CNTOS-64-S11 testbox]$ cc -g t1.c -o t1
[sand@PS-CNTOS-64-S11 testbox]$ valgrind --tool=memcheck ./t1
==20859== Memcheck, a memory error detector
==20859== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==20859== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==20859== Command: ./t1
==20859==
==20859== Invalid free() / delete / delete[]
==20859== at 0x4A05A31: free (vg_replace_malloc.c:325)
==20859== by 0x4004FF: main (t1.c:8)
==20859== Address 0x4c26040 is 0 bytes inside a block of size 100 free'd
==20859== at 0x4A05A31: free (vg_replace_malloc.c:325)
==20859== by 0x4004F6: main (t1.c:7)
==20859==
==20859==
==20859== HEAP SUMMARY:
==20859== in use at exit: 0 bytes in 0 blocks
==20859== total heap usage: 1 allocs, 2 frees, 100 bytes allocated
==20859==
==20859== All heap blocks were freed -- no leaks are possible
==20859==
==20859== For counts of detected and suppressed errors, rerun with: -v
==20859== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
[sand@PS-CNTOS-64-S11 testbox]$
[sand@PS-CNTOS-64-S11 testbox]$ valgrind --tool=memcheck --leak-check=full ./t1
==20899== Memcheck, a memory error detector
==20899== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==20899== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==20899== Command: ./t1
==20899==
==20899== Invalid free() / delete / delete[]
==20899== at 0x4A05A31: free (vg_replace_malloc.c:325)
==20899== by 0x4004FF: main (t1.c:8)
==20899== Address 0x4c26040 is 0 bytes inside a block of size 100 free'd
==20899== at 0x4A05A31: free (vg_replace_malloc.c:325)
==20899== by 0x4004F6: main (t1.c:7)
==20899==
==20899==
==20899== HEAP SUMMARY:
==20899== in use at exit: 0 bytes in 0 blocks
==20899== total heap usage: 1 allocs, 2 frees, 100 bytes allocated
==20899==
==20899== All heap blocks were freed -- no leaks are possible
==20899==
==20899== For counts of detected and suppressed errors, rerun with: -v
==20899== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
[sand@PS-CNTOS-64-S11 testbox]$
One possible fix:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *x = malloc(100);
free(x);
x=NULL;
free(x);
return 0;
}
[sand@PS-CNTOS-64-S11 testbox]$ vim t1.c
[sand@PS-CNTOS-64-S11 testbox]$ cc -g t1.c -o t1
[sand@PS-CNTOS-64-S11 testbox]$ ./t1
[sand@PS-CNTOS-64-S11 testbox]$
[sand@PS-CNTOS-64-S11 testbox]$ valgrind --tool=memcheck --leak-check=full ./t1
==20958== Memcheck, a memory error detector
==20958== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==20958== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==20958== Command: ./t1
==20958==
==20958==
==20958== HEAP SUMMARY:
==20958== in use at exit: 0 bytes in 0 blocks
==20958== total heap usage: 1 allocs, 1 frees, 100 bytes allocated
==20958==
==20958== All heap blocks were freed -- no leaks are possible
==20958==
==20958== For counts of detected and suppressed errors, rerun with: -v
==20958== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
[sand@PS-CNTOS-64-S11 testbox]$
Check out the blog on using Valgrind Link
- Dynamic Memory Allocation and Deallocation in C++
double free or corruption
Error in C++- How to Avoid
double free or corruption
Error in C++
This tutorial will discuss issues that occur in dynamic memory allocations in C++. When using heap memory, we come across many issues that are very important to be addressed while doing heap memory management.
First, we will discuss how we allocate memory and the different methods provided in C++; then, we will move towards the causes and solutions of double free or corruption
error in C++.
Dynamic Memory Allocation and Deallocation in C++
C++ allows us to allocate variable or array memory during runtime. This is referred to as dynamic memory allocation.
In other programming languages, such as Java and Python, the compiler maintains variable memory automatically. However, this is not the case in C++.
In C++, we must manually deallocate dynamically allocated memory after we no longer require it. We may allocate and deallocate memory dynamically using the new
and delete
functions.
There are other two functions, i.e., malloc
and free
, which are also included in C++ for dynamic memory allocation and deallocation.
Consider an example below demonstrating the use of new
and delete
functions.
#include <iostream>
using namespace std;
int main() {
int* ptr;
ptr = new int;
*ptr = 40;
cout << *ptr;
delete ptr;
return 0;
}
We dynamically allocated memory for an int
variable using the’ new’ operator. It’s worth noting that we used the reference variable ptr
to allocate memory dynamically.
The new
operator returns the memory location’s address. In the case of an array, the new
operator returns the address of the array’s first element.
We can deallocate the memory used by a dynamically declared variable after we no longer need to utilize it. The delete
operator is used for this.
It gives the memory back to the operating system. This is referred to as memory deallocation.
The next example will show you a demonstration of malloc
and free
functions.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int* ptr2 = (int*) malloc(sizeof(int));
*ptr2 = 50;
cout << *ptr2;
free(ptr2);
return 0;
}
In C++, the malloc()
method assigns a pointer to a block of uninitialized memory. The cstdlib
header file defines it.
malloc
takes in as a parameter the size of memory you need to allocate and returns a void pointer pointing to the allocated memory block. Hence it can be typecast according to our requirements.
On the other hand, the free()
method deallocates the memory allocated using the malloc
function. It returns that memory to the operating system and avoids memory leakage issues.
double free or corruption
Error in C++
Double-free errors occur when free()
is used more than once with the same memory address as an input.
Calling free()
on the same variable twice can result in a memory leak. When a software runs free()
twice with the same parameter, the memory management data structures in the application get corrupted, allowing a malicious user to write values in any memory area.
This corruption can cause the program to crash or change the execution flow in some cases. An attacker can mislead a program into executing a code of their choice by overwriting specific registers or memory regions, resulting in an interactive shell with elevated rights.
A linked list of free buffers is read when a buffer is free()
’d to reorganize and combine the pieces of free memory (to allocate larger buffers in the future). These chunks are organized in a double-linked list with links to the chunks before and after them.
An attacker might write arbitrary values in memory by unlinking an unused buffer (which happens when free()
is invoked), effectively overwriting valuable registers, and launching shellcode from its buffer.
Consider an example below.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int* ptr2 = (int*) malloc(sizeof(int));
*ptr2 = 50;
cout << *ptr2;
free(ptr2);
free(ptr2);
return 0;
}
Output:
free(): double free detected in cache 2
Aborted
In the code snippet above, we have used the free()
function twice, which means we are trying to free up the memory that is already free and is no more allocated. This creates a memory leakage issue and is the root cause of crashing the code.
There are many other situations as well that can encounter such errors. But there are three common (and often overlapping) reasons for double-free vulnerabilities.
- Error conditions and other unusual situations
- After the memory space has been released, it is used.
- Confusion about which section of the program is in charge of memory freeing
Although some double-free vulnerabilities aren’t much more complex than the preceding example, most of them are distributed across hundreds of lines of code or even multiple files. Programmers appear to be particularly prone to freeing global variables multiple times.
How to Avoid double free or corruption
Error in C++
This type of vulnerability can be avoided by assigning NULL
to our pointer whenever it becomes free (i.e., the memory pointed by this pointer gets free). Following that, most of the heap managers ignore the free null pointers.
It is recommended to null all deleted pointers and check whether the reference is null
or not before freeing it. At the start of our code, we must initialize the null
pointer before using that pointer in any case.
Я полагаю, что корень вашей проблемы вызван распределением
valueArray
и тем фактом, что вы выходите за пределы итерации.Строка
valueArray=new int[value];
инициализируетvalueArray
массивом размераvalue
, который является неинициализированной переменной. Возможно, вы хотели использоватьnoItems
?Также, как указал сонгюаньяо в комментариях, ваши
for
циклы выглядят какfor(int i=1;i<=noItems;i++)
, который начинает счетчик в1
и заканчивается счетчиком вnoItems
, что является ошибочным. Во многих языках, включая C++ , массивы начинаются с индекса0
(то есть первый элемент —array[0]
, а неarray[1]
), а последний элемент-единица минус размер массива (таким образом, последний элемент массива с 5 элементами —array[4]
).Если вы измените свой цикл
for
, чтобы начать с 0 и закончить один элемент передnoItems
, Вы должны быть золотыми. Это будетfor(int i = 0; i < noItems; i++ )
Что, вероятно, происходит с меньшими выделениями, так это то, что различные куски памяти расположены последовательно в одной и той же области кучи памяти, поэтому, когда вы переполняя буфер данными, вы разбиваете бухгалтерские данные
new
.Когда у вас есть большие выделения, новая память не может поместиться так же чисто в свободное пространство кучи, поэтому распределитель в конечном итоге оставляет некоторое свободное пространство между выделениями. Таким образом, небольшой перерасход не уничтожает кучу информации.
NVD Categorization
CWE-415: Double Free: The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.
Description
Double free errors occur when free()
is called more than once with the same memory address as an argument.
Calling free()
twice on the same value can lead to memory leak. When a program calls free()
twice with the same argument, the program’s memory management data structures become corrupted and could allow a malicious user to write values in arbitrary memory spaces. This corruption can cause the program to crash or, in some circumstances, alter the execution flow. By overwriting particular registers or memory spaces, an attacker can trick the program into executing code of their own choosing, often resulting in an interactive shell with elevated permissions.
When a buffer is free()
‘d, a linked list of free buffers is read to rearrange and combine the chunks of free memory (to be able to allocate larger buffers in the future). These chunks are laid out in a double linked list which points to previous and next chunks. Unlinking an unused buffer (which is what happens when free()
is called) could allow an attacker to write arbitrary values in memory; essentially overwriting valuable registers, calling shellcode from its own buffer.
Consequences
- Access control: Doubly freeing memory may result in a write-what-where condition, allowing an attacker to execute arbitrary code.
Exposure period
- Requirements specification: A language which handles memory allocation and garbage collection automatically might be chosen.
- Implementation: Double frees are caused most often by lower-level logical errors.
Platform
- Language: C, C++, Assembly
- Operating system: All
Required resources
Any
Severity
High
Likelihood of exploit
Low to Medium
Doubly freeing memory can result in roughly the same write-what-where condition that the use of previously freed memory will.
Examples
While contrived, this code should be exploitable on Linux distributions that don’t ship with heap-chunk check summing turned on.
#include <stdio.h>
#include <unistd.h>
#define BUFSIZE1 512
#define BUFSIZE2 ((BUFSIZE1/2) - 8)
int main(int argc, char **argv) {
char *buf1R1;
char *buf2R1;
char *buf1R2;
buf1R1 = (char *) malloc(BUFSIZE2);
buf2R1 = (char *) malloc(BUFSIZE2);
free(buf1R1);
free(buf2R1);
buf1R2 = (char *) malloc(BUFSIZE1);
strncpy(buf1R2, argv[1], BUFSIZE1-1);
free(buf2R1);
free(buf1R2);
}
Double free vulnerabilities have three common (and sometimes overlapping) causes:
- Error conditions and other exceptional circumstances
- Usage of the memory space after it’s freed.
- Confusion over which part of the program is responsible for freeing the memory
Although some double free vulnerabilities are not much more complicated than the previous example, most are spread out across hundreds of lines of code or even different files. Programmers seem particularly susceptible to freeing global variables more than once.
- Implementation: Ensure that each allocation is freed only once. After freeing a chunk, set the pointer to NULL to ensure the pointer cannot be freed again. In complicated error conditions, be sure that clean-up routines respect the state of allocation properly. If the language is object oriented, ensure that object destructors delete each chunk of memory only once.
- Buffer overflow attack
Marikoo 0 / 0 / 0 Регистрация: 27.05.2015 Сообщений: 50 |
||||
1 |
||||
12.03.2019, 13:49. Показов 8801. Ответов 6 Метки нет (Все метки)
на последней строчке валиться программа, double free or corruption (out)
__________________
0 |
Нарушитель 8388 / 4391 / 1009 Регистрация: 12.03.2015 Сообщений: 20,566 |
|
12.03.2019, 13:55 |
2 |
Размер вылезает за кусок выделенной памяти. В приёмнике должно быть байт не меньше, чем указано в 3 параметре memcpy(). А ты хочешь на 1 байт больше.
0 |
Marikoo 0 / 0 / 0 Регистрация: 27.05.2015 Сообщений: 50 |
||||
12.03.2019, 13:59 [ТС] |
3 |
|||
8 байт убераю +1, та же ошибка
0 |
zayats80888 5695 / 3134 / 1306 Регистрация: 07.02.2019 Сообщений: 7,875 |
||||
12.03.2019, 14:04 |
4 |
|||
std::cout << sizeof(brf.str().length()+1)<<std::endl;
а так?
0 |
Нарушитель 8388 / 4391 / 1009 Регистрация: 12.03.2015 Сообщений: 20,566 |
|
12.03.2019, 14:07 |
5 |
8 байт Если ты хочешь скопировать строку, то почему не юзаешь тупо strcpy()? ——
0 |
lArtl 322 / 174 / 78 Регистрация: 09.10.2014 Сообщений: 809 |
||||
12.03.2019, 14:13 |
6 |
|||
Добавлено через 3 минуты Вы там чего творите?
0 |
0 / 0 / 0 Регистрация: 27.05.2015 Сообщений: 50 |
|
12.03.2019, 15:05 [ТС] |
7 |
спасибо, ошибка пропала
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
12.03.2019, 15:05 |
7 |
title | description | ms.date | f1_keywords | helpviewer_keywords | ||
---|---|---|---|---|---|---|
Error: double-free |
Source examples and live debug screenshots for double free errors. |
03/02/2021 |
double-free |
|
Error: double-free
Address Sanitizer Error: Deallocation of freed memory
In C, you can call free
erroneously. In C++, you can call delete
more than once. In these examples, we show errors with delete
, free
, and HeapCreate
.
Example C++ — double operator delete
// example1.cpp // double-free error int main() { int *x = new int[42]; delete [] x; // ... some complex body of code delete [] x; return 0; }
To build and test this example, run these commands in a Visual Studio 2019 version 16.9 or later developer command prompt:
cl example1.cpp /fsanitize=address /Zi devenv /debugexe example1.exe
Resulting error — double operator delete
:::image type=»content» source=»media/double-free-example-1.png» alt-text=»Screenshot of debugger displaying double-free error in example 1.»:::
Example ‘C’ — double free
// example2.cpp // double-free error #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { char* x = (char*)malloc(10 * sizeof(char)); memset(x, 0, 10); int res = x[argc]; free(x); // ... some complex body of code free(x + argc - 1); // Boom! return res; }
To build and test this example, run these commands in a Visual Studio 2019 version 16.9 or later developer command prompt:
cl example2.cpp /fsanitize=address /Zi devenv /debugexe example2.exe
Resulting error — double free
:::image type=»content» source=»media/double-free-example-2.png» alt-text=»Screenshot of debugger displaying double-free error in example 2.»:::
Example — Windows HeapCreate
double HeapFree
// example3.cpp // double-free error #include <Windows.h> #include <stdio.h> int main() { void* newHeap = HeapCreate(0, 0, 0); void* newAlloc = HeapAlloc(newHeap, 0, 100); HeapFree(newHeap, 0, newAlloc); HeapFree(newHeap, 0, newAlloc); printf("failuren"); return 1; }
To build and test this example, run these commands in a Visual Studio 2019 version 16.9 or later developer command prompt:
cl example3.cpp /fsanitize=address /Zi devenv /debugexe example3.exe
Resulting error — Windows HeapCreate
double HeapFree
:::image type=»content» source=»media/double-free-example-3.png» alt-text=»Screenshot of debugger displaying double-free error in example 3.»:::
See also
AddressSanitizer overview
AddressSanitizer known issues
AddressSanitizer build and language reference
AddressSanitizer runtime reference
AddressSanitizer shadow bytes
AddressSanitizer cloud or distributed testing
AddressSanitizer debugger integration
AddressSanitizer error examples
One of the most common memory corruption error usually found in an application is “Double Free” error. Double free error is caused by freeing same memory location twice by calling free() on the same allocated memory. Below is a sample “Double Free” error code,
char* Y = (char*)malloc(20);
…….
If (X)
{
free(Y);
}
……..
free(Y)
It becomes too complex to find such errors in a bunch of files in an application.
How memory is allocated ….???
Consider an application which makes a request to the OS (Operating System) for some amount of memory to be allocated. Usually OS projects to the application as if the requested block of memory is one chunk of memory block, but actually the memory will be segregated in different places. OS usually maintains 2 pointers for each memory locations, 1st pointer will be having location details of the previous free memory and the 2nd pointer will be having location details to the next free memory location. When you “free()” memory locations,
free(X)
free(Y)
Consider “A” and “B” points to the two pointers of “X” memory location and “C” and “D” points to the two pointers of “Y” memory location.
A —-> 1st pointer of freed “X” memory block holds the previous random memory location
B —-> 2nd pointer of freed “X” memory block holds “y” freed memory location (“Y” memory location is next to “X” memory location)
C —-> 1st pointer of freed “Y” will hold “X” freed memory location (“X” memory location is previous to “Y” memory location)
D —-> 2nd pointer of freed “Y” will holds the next random memory location
It’s similar to Doubly-linked list.
Here “A” will be holding previous free random memory location, “B” will be holding “Y” memory location and “C” will be holding “X” memory location and “D” will be holding next free random memory location.
What causes a Double Free Vulnerability ….???
To trigger a double Free Vulnerability, same memory location should be freed (“free()”) twice. Have a look at the first sample code, variable “Y” is freed twice
free(Y) # freed first time
free(Y) # freed again second time
When same memory allocated variable is freed twice, then multiple memory location pointers will be pointing to the same freed memory location.
Later, if new memory is allocated to “Z”, there will be an undesirable condition which may lead to memory corruption.
char* Z = (char*)malloc(20);
How to avoid Double Free error while coding …?
One of the ways to avoid Double Free error in the code is by assigning the pointer to null after it’s been freed once.
char* Y = (char*)malloc(20);
…….
If (X)
{
free(Y);
Y = NULL;
}
……..
free(Y) # It’s nothing but free(NULL)
free(NULL) will be a dead code which particularly does nothing.
To detect this kind of memory corruption errors Open-Source tools like Valgrind or GNU Project debugger are very much handy which helps to analyze code in a better way.
– Shashi Kiran
The error of double free or corruption in C means that our program somehow invokes the free() C object with an illegal pointer variable. When we use smart pointers such as shared_ptr, we must check because if we call the function get(), we are directly using the raw pointer. We plan to assign this to a smart pointer for continuing reference. This Corruption is the root cause of the crashing of the code. We use the free() function to dislocate the heap memory typically. The heap memory has mainly used the function of our operating system to manage the memory locations. So here is the mistake when our code does not own this pointer until we copy the code.
When the pointer is null:
Here we just show our free() function how it works at the start; we include libraries and namespace standards and start the main body of the code initialized the integer variable and also initialized a pointer with the null to avoid the error of double free or corruption and other pointers have the value of our integer. Then we use the if-else statement to check the Null pointer and the pointer that has our integer value. After the condition, we call our function to reallocate our pointer.
#include
using namespace std;
int main()
{
int x = 5;
int *ptr1 = NULL;
int *ptr2 = &x;
if(ptr1)
{
cout << “Pointer is not Null” << endl;
}
else
{
cout << “Pointer is Null” << endl;
}
free(ptr1);
cout << *ptr2;
}
<img alt=»» data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/03/echo/Error-Double-Free-or-Corruption-1.png» data-lazy- height=»352″ src=»data:image/svg xml,” width=”705″>
Upon execution, the output will look like this:
<img alt=»» data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/03/echo/Error-Double-Free-or-Corruption-2.png» data-lazy- height=»101″ src=»data:image/svg xml,” width=”730″>
How it’s Accrue:
This is accrued if the pointer is using memory allocation or calling the free() function in C directly sometimes. It could also be accrued when free() is called as an argument to the same memory location one or more than one time. The code’s memory management data structure has become corrupted or cannot allow a suspicious end user to enter the values in a random memory location. If a code calls the free() function with the same memory location more than once.
Also, if we delete the same entry two times and delete something that was not allocated in the memory heap. Thus the pointers are the direct cause of this error.
#include
#include
#include
int main(){
std::vector<int> vec{0, 1, 2};
std::vector<int>::iterator it = std::max_element(vec.begin(), vec.end());
std::vector<int> vec2{3, 4, 5};
vec.insert(vec.end(), vec2.begin(), vec2.end());
vec.erase(it);
for (auto &n : vec){
std::cout << n << std::endl;
}
}
<img alt=»» data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/03/echo/Error-Double-Free-or-Corruption-3.png» data-lazy- height=»282″ src=»data:image/svg xml,” width=”712″>
First, we integrate three header libraries; one is #include, in Standard Template Library, it is a template class in the programming language. It is a sequence container that saves elements. Mainly used to support the Dynamic data in C programming language. We can expand the vectors, but it depends on the elements that these vectors contain along with them.
The second header file is #include that provides us many functionalities that could be for many purposes, like sorting the element, supporting search algorithm, multiplying the values, counting variables, and so on. Last but not least, that is #include that purpose is to support our input-output stream. After libraries, we start our main body where we use standards with the vectors and assign variables having integer data-type and assign values to this variable.
Here is our statement where we assign our variable along with its start and endpoint through the function maz_element. Again repeat the statement, but we change our values to another variable this time. Then we use the insert function and pass the parameters that are the endpoint of our previous variable, the start point of the 2nd variable, and the endpoint of the variable. The erase() function is used to erase a single element from the vector and is also used to modify the size of the vector. At last, we use for loop with the limit of our first variable, and in the loop, we display the variable that we initialized in our loop.
<img alt=»» data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/03/echo/Error-Double-Free-or-Corruption-4.png» data-lazy- height=»121″ src=»data:image/svg xml,” width=”761″>
How to Avoid:
We can avoid this type of vulnerability; we must always assign NULL to our pointer when it becomes free. Mostly heap managers ignored the free null pointers subsequently. This is the best practice that we null all the deleted pointers as well as we must also set a check whether the pointer is null or not before we free the pointer. We must initialize the pointer null at the start of our code. Like when we try to use cout(std::cout) statement.
#include
using namespace std;
int main()
{
int * i = new int();
delete i;
cout<<i;
cout<<“npointer delete successfully”;
delete i;
cout<<i;
return 0;
}
<img alt=»» data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/03/echo/Error-Double-Free-or-Corruption-5.png» data-lazy- height=»251″ src=»data:image/svg xml,” width=”712″>
The header file is included. Then we write using namespace standard and start the body of the main program. We initialized the pointer with the integer data type. Here we assign null to the pointer and print the pointer. After assigning the null, we delete the pointer and print the message of success. At last, we again check our pointer, and you can see there is no pointer existing in our memory heap.
<img alt=»» data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/03/echo/Error-Double-Free-or-Corruption-6.png» data-lazy- height=»114″ src=»data:image/svg xml,” width=”756″>
Conclusion:
In this article, we briefly describe the error double free or corruption. Then we have reallocated our memory by using our () function and discussed the causes of the error and used the example of erasing() function. In the end, we have provided a solution a simple and logical solution to this error in a very easy way.