473,503 Members | 241 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Copy Constructor segmentation fault

Kindly help me explain the behaviour of defult copy constructor . Why
the destructor is freeing the SAME memory twice , though it was
allocated just once .

#include<iostream>
using namespace std;
class var_array
{
private:
int *data; // The data
const int size; // The size of the data
public:
var_array(const int _size):
size(_size)
{
data = new int[size];
memset(data, '\0',
size * sizeof(int));
}
// Destroy the var_array
~var_array(void) {
delete []data;
}
public:
// Get an item in the array
int &operator [] (
// Index into the array
const unsigned index
)
{
return (data[index]);
}
};
static void store_it(
var_array test_array
)
{
test_array[7] = 7;
}
int main()
{
var_array test_array(30);
store_it(test_array);
return (0);
}

Apr 5 '06 #1
2 5123

pr********@gmail.com wrote:
Kindly help me explain the behaviour of defult copy constructor . Why
the destructor is freeing the SAME memory twice , though it was
allocated just once .

#include<iostream>
using namespace std;
class var_array
{
private:
int *data; // The data
const int size; // The size of the data
public:
var_array(const int _size):
size(_size)
{
data = new int[size];
memset(data, '\0',
size * sizeof(int));
}
// Destroy the var_array
~var_array(void) {
delete []data;
}
public:
// Get an item in the array
int &operator [] (
// Index into the array
const unsigned index
)
{
return (data[index]);
}
};
static void store_it(
var_array test_array
)
{
test_array[7] = 7;
}
int main()
{
var_array test_array(30);
store_it(test_array);
return (0);
}


In store_it() method the argument is of type var_array.
So once you pass object of var_array as an argument, copy constructor
is called.
If not provided compiler provides the default copy constructor, which
copies the data bit by bit.
Now the the pointer is copied to the local object which points to
memory allocated by the calling argument.
As the object goes out of scope the destructor is called, which delete
[]s the data.
Now the control returns to main().
Now in main() the test_array object holds the data variable which
points to a location that has been deleted(a dangling reference).
When main exits the destructor is called for the test_array object.
Trying to delete a pointer that has already been deleted causes a
segmentation fault.

Regards
Sunil Varma

Apr 5 '06 #2
pr********@gmail.com wrote:
Kindly help me explain the behaviour of defult copy constructor . Why
the destructor is freeing the SAME memory twice , though it was
allocated just once .

#include<iostream>
Nitpick: You don't use this header.
using namespace std;
class var_array
{
private:
int *data; // The data
const int size; // The size of the data
public:
var_array(const int _size):
size(_size)
{
data = new int[size];
memset(data, '\0',
size * sizeof(int));
}
// Destroy the var_array
~var_array(void) {
delete []data;
}
public:
// Get an item in the array
int &operator [] (
// Index into the array
const unsigned index
)
{
return (data[index]);
}
};
It's fine if you're doing this as an exercise, but in general, prefer
to use std::vector, which provides the same functionality in a working,
standard form.
static void store_it(
Using static to indicate "local to this translation unit" has been
deprecated in C++. Use anonymous namespaces instead.
var_array test_array
The basic problem is this: you are copying the object, and the default
copy constructor just copies its members "dumbly." It doesn't allocate
new memory and copy the existing array values into the new memory; it
just copies the address of the existing array into the new object that
is created here. Then, when the function completes, it executes the
destructor, deleting the memory that is pointed to in both by your
var_array classes, and Bang! you have a dangling pointer.

You should pass this parameter by reference rather than by value to
prevent the invocation of the copy constructor. If you don't need to
modify it, pass it by const reference (you'll also need to add a const
version of operator[]). Alternately, you could write a copy constructor
(and assignment operator!) that gives whatever non-default behavior you
want. Moreover, you could use a smart pointer or smart array such as
those supplied by Boost to manage the memory. The best option, though,
is to use std::vector.
)
{
test_array[7] = 7;
}
int main()
{
var_array test_array(30);
store_it(test_array);
return (0);
}


Cheers! --M

Apr 5 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

42
5720
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same...
3
11380
by: Zheng Da | last post by:
Program received signal SIGSEGV, Segmentation fault. 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 (gdb) bt #0 0x40093343 in _int_malloc () from /lib/tls/libc.so.6 #1 0x40094c54 in malloc...
5
2976
by: Fra-it | last post by:
Hi everybody, I'm trying to make the following code running properly, but I can't get rid of the "SEGMENTATION FAULT" error message when executing. Reading some messages posted earlier, I...
18
26058
by: Digital Puer | last post by:
Hi, I'm coming over from Java to C++, so please bear with me. In C++, is there a way for me to use exceptions to catch segmentation faults (e.g. when I access a location off the end of an array)?...
27
3314
by: Paminu | last post by:
I have a wierd problem. In my main function I print "test" as the first thing. But if I run the call to node_alloc AFTER the printf call I get a segmentation fault and test is not printed! ...
1
3183
by: samuel.y.l.cheung | last post by:
Hi, I wrote a template to use copy() algorithm, called copyAll: template<class T> void copyAll(const T& src , T& dest ) { copy (src.begin(), src.end(), back_inserter(dest)); } but when I...
5
2430
by: sarathy | last post by:
Hi, I need to see the output of the program when no copy constructor is used. Since by default, there is an implicit one, how should i perform the override, so as to totally remove the copy...
7
5856
by: pycraze | last post by:
I would like to ask a question. How do one handle the exception due to Segmentation fault due to Python ? Our bit operations and arithmetic manipulations are written in C and to some of our...
3
5132
by: madunix | last post by:
My Server is suffering bad lag (High Utlization) I am running on that server Oracle10g with apache_1.3.35/ php-4.4.2 Web visitors retrieve data from the web by php calls through oci cobnnection...
0
7203
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7089
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7282
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6995
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5581
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5017
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4678
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1515
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
738
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.