Reputation: 13
I faced some problem when i use Reference pointer type as parameter.
first, this is my code.
#include<iostream>
using namespace std;
void test(int*& ptr);
int main(void)
{
int* ptr = new int[1];
ptr[0] = 100;
cout << ptr[0];
test(ptr);
cout << ptr[0] << '\t' << ptr[1];
}
void test(int*& ptr)
{
int* tmp = new int[2];
tmp[0] = 1;
tmp[1] = 2;
int* tmp2 = ptr;
ptr = tmp;
cout << ptr[0] << '\t' << ptr[1];
delete[]tmp2;
}
and when compiled this code, the output is
100
1 2
this output is what i want to get
but when i debug this code,
Exception thrown: read access violation.
this error has occurred.
how to avoid this error, and what is my fault? :(
and what should i do when reallcoate parameter's memory without using reference type?
Upvotes: 0
Views: 66
Reputation: 66194
The reference isn't the problem. It's your dynamic memory management that is dreadfully broken.
#include <iostream>
using namespace std;
void test(int *&ptr);
int main(void)
{
int *ptr = new int[1]; // allocates a sequence of 1
ptr[0] = 100;
cout << ptr[0];
test(ptr); // sends pointer to sequence by reference to test
cout << ptr[0] << '\t' << ptr[1];
}
void test(int *&ptr)
{
int *tmp = new int[2]; // allocates a sequence of size 2
tmp[0] = 1;
tmp[1] = 2;
int *tmp2 = ptr; // stores original passed-in pointer to tmp2
ptr = tmp; // assigns new sequence pointer to reference argument (leaks original)
cout << ptr[0] << '\t' << ptr[1];
delete[] ptr; // deletes the new sequence. (leaves dangling pointer)
}
What you seem to be trying to do is this:
#include <iostream>
using namespace std;
void test(int *&ptr);
int main(void)
{
int *ptr = new int[1];
ptr[0] = 100;
cout << ptr[0] << '\n';
test(ptr);
cout << ptr[0] << '\t' << ptr[1] << '\n';
delete [] ptr;
}
void test(int *&ptr)
{
delete [] ptr; // delete original sequence
ptr = new int[2]; // create new sequence
ptr[0] = 1;
ptr[1] = 2;
}
Stop Using Raw Pointers
Alternatively, use smart pointers to manage this.
#include <iostream>
#include <memory>
using namespace std;
void test(std::unique_ptr<int[]>& ptr);
int main(void)
{
std::unique_ptr<int[]> ptr = std::make_unique<int[]>(1);
ptr[0] = 100;
cout << ptr[0] << '\n';
test(ptr);
cout << ptr[0] << '\t' << ptr[1] << '\n';
}
void test(std::unique_ptr<int[]>& ptr)
{
ptr = std::make_unique<int[]>(2);
ptr[0] = 1;
ptr[1] = 2;
}
Or better still, just use a std::vector<int>
Upvotes: 1