Mailinglist Archive: opensuse-programming (96 mails)

< Previous Next >
Re: [suse-programming-e] Pointer strangeness
  • From: Jerry Feldman <gfeldman@xxxxxxxxx>
  • Date: Mon, 31 Mar 2003 07:14:15 -0500
  • Message-id: <20030331071415.348905fa.gfeldman@xxxxxxxxx>
Remember that tmp is an automatic variable. When you exit the HelloClass
constructor, the storage for tmp is released and may (or let's say will
be) used in another function. Automatic variables are fundamental to C
and C++. Any variable you define within the scope of a function that
does not have the static keyword is an automatic variable, and has block
scope.

Pointers are very simple, they are simply data types that hold a memory
address.

char *s = "abc";
s will contain the address of a 4 byte chunk of memory containing 'a'
'b' 'c' '\0'

string *str = new string("abc");
Similarly, str will contain the address of a string class that you have
allocated with the new operator.

Note that "string" is a C++ class, and has overhead, such as
constructors, destructors, manipulation functions, and several variables
as well as a pointer to the actual data.

Let's get back to pointers. In the above example, str points to a string
class. Now, let's change it a bit.
str = new string("def");

In this case, we have replaced the existing pointer value with a new
one, thus causing a memory leak. That is because we did not delete the
space for the old value. Unlike Java, neither C nor C++ will
automatically reclaim unused allocated memory. Java has a builtin
garbage collection system. So, as a C or C++ programmer, you need to
make sure that memory you allocate is reclaimed. Within a class, that
may be done in a destructor or in your case, HelloClass::setMessagePtr
should check this->messagePtr to see if it already contains a pointer.
Also, you do not need to use this-> in a class member function, it is
assumed.

I hope that the above information has been useful.

< Previous Next >
List Navigation
Follow Ups
References