I have the next following code :
#include<iostream>
using namespace std;
void test(char arr[], int size){
char* newA = new char[5];
delete[] arr; // this line cause the breakpoint
arr = newA;
}
void main(){
char* aa = new char[5];
test(aa,5);
aa[0] = 's';
}
When I run this code I see that the variable "aa" at index zero is 's' then the breakpoint is triggered.
You are passing arr
by value, so this line
arr = newA;
has no effect in the caller side. So you are reading from a deleted array here:
aa[0] = 's';
This is undefined behaviour. You can fix this in three ways:
Pass a reference:
void test(char*& arr, int size) { .... }
Return the pointer:
char* test(char* arr, int size) {
delete[] arr;
return new char[5];
}
Or, better, use well behaved standard library types such as std::string
.