473,407 Members | 2,676 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

Good links for handling with pointers?

Hello,

I still have massive problems with handling with pointers when I use
them through methods or much more complicated constructs.
Do you have any good and helpful links which describe these issues
carefully?

Thanks,
Markus
Oct 21 '07 #1
7 1478
Hello,

Alf P. Steinbach schrieb:
Exactly what is the problem?
I often get "segmentation fault" errors because with catchier
constructs, I'm not sure anymore if I should use a reference or a
pointer an so on.
Then often I have the problem that I have a method which should obtain a
non pointer variable, but in this case I only have a pointer to this
variable, and what then?

Let's see my actual example which leads to a "segemntation fault" or
doesn't even compile:

----------------------------------------------------

class Adjazenzmatrix
--------------------
..
..
..
Knoten *knoten[groesse]; //I define a list of size "groesse" of pointers
to "Knoten".

for (int i = 0; i < groesse; i++) {
knoten[i] = new Knoten(i); initialize every element as new Knoten
..
..
..//and so on.....

//This is weird. Here I want to iterate over every element of "knoten",
but....

for (int kBez = 0; kBez < groesse; kBez++) {
findKomponenten(knoten[kBez]); //LINE 178
}
}
-------------------------------------------

....I get the following error message while compiling:

markus@gentoo ~/CPP-Programme/ $ g++ *.cpp -o Main `pkg-config gtkmm-2.4
--cflags --libs`
Adjazenzmatrix.cpp: In member function »void
Adjazenzmatrix::berechneEigenschaften()«:
Adjazenzmatrix.cpp:178: Fehler: ungültige Umwandlung von »Knoten*« in »int«
Adjazenzmatrix.cpp:178: Fehler: Argument 1 von »Knoten::Knoten(int)«
wird initialisiert

Which means something like:
Invalid conversion of "Knoten*" to "int.
Error: Argument 1 of Knoten::Knoten(int) will be initialized.

What does that mean?

Here is the method findKomponenten:
-------------------------------------------------
void Adjazenzmatrix::findKomponenten(Knoten k) {
k.setVisited();
if (k.getNachbarknotenAnzahl() 0) {
int nachbarCounter = 0;
Knoten neuer = k.getNachbarknoten(nachbarCounter);
while (neuer.isVisited() == false) {
findKomponenten(neuer);
nachbarCounter++;
}
}
}
-------------------------------------------------
So where is there an int I obviously convert to?

Constructor of class Knoten:
------------------------------------------
Knoten::Knoten(int nr) {
knotenNr = nr;
visited = false;
nachbarknoten = new ListT<Knoten>;
}

As you can see, I use a self programmed dynamically list in this class.
Now it's getting complicated for me. Later in this class, I initialize
new ListT-elements which are also "Knoten". I want to access those
elements from Adjazenzmatrix so I have sometimes already pointer with
the deep of two and then I'm not sure anymore how to handle it.
I don't know if I should return a pointer or not or as I already said,
the return values doesn't "fit" to the class which invokes the methods
of the instances because the method returns a non pointer value but in
the invoking class I have a pointer.
I alwasy fight with such problems, so I need to get deeper into the
knowledge of handling with pointer.
Markus
Oct 22 '07 #2
Hello,

you are surely right when you say that I'd rather use these libraries.
But my target is it to improve my C++ skills. I think that perfect
handling with pointers is one of the basics if someone wants to cope
with C or C++. And I think that my pointer knowledge is still insufficient.
Markus
Oct 22 '07 #3
Markus Pitha wrote:
Hello,

you are surely right when you say that I'd rather use these libraries.
But my target is it to improve my C++ skills. I think that perfect
handling with pointers is one of the basics if someone wants to cope
with C or C++. And I think that my pointer knowledge is still
insufficient.
Uhm, handling of dynamic allocation is hardly one of the _basics_. It is a
necessary skill, that much is true. And pointers are part of the core
language. However, I think that acquirering pointer skills should come
somewhat late in the learning process. The reason is that proper dynamic
allocation and deallocation requires awareness of many traps created by
their interaction with other parts of the language, most notably
try-throw-catch. If you dive into these issues early, you may pick up
habits that are dangerous but whose dangers can only be seen from a more
advanced perspective.

A fundamental rule for dynamic allocation is that each allocation has to be
matched by one and only one deallocation along _each_ possible path of
execution. This requires a somewhat global perspective on your code. You
cannot verify this property by looking at your code locally. Since a throw
hidden in a function can divert the path of execution at any given moment,
this is very hard to ensure.

For starters, you should stick to the rule that allocation of pointers is
done in a constructor and the matching deallocation goes into the code of
the destructor. That will ensure proper matching of allocation and
deallocation (unless the constructor throws after an allocation:-).

Another hint is: use debugging tools like valgrind to check all your
programs for memory correctness. Dereferencing dangling pointers is
undefined behavior and does not always show as a crash.
Anyway, the most important knowledge about dynamic allocation is the many
ways of using the STL instead.
Best

Kai-Uwe Bux
Oct 22 '07 #4
Hello,

acutally I'm not a total beginner with pointers but my current problem
annoys me, so I'm not experienced enough. It is obvious that I won't
come to a conclusion for now and I decided to rewrite the non working
parts of my program with STL. Maybe it's getting clearer for me then.

Markus
Oct 22 '07 #5
On Oct 22, 2:41 pm, "Alf P. Steinbach" <al...@start.nowrote:

[...]
Use boost::shared_ptr instead of raw pointers.
That's bad advice, generally. There are cases where
boost::shared_ptr is appropriate, but there are lots of cases
where it isn't. Expecting it to solve all of your problems will
only lead to more problems.

[...]
Instead, what you probably need most is to discover that the standard
library's collection classes solve most of the problems you're
struggling with.
Some pointer usage will remain.
And most of it will be navigation. Where boost::shared_ptr
isn't appropriate.
For that, use smart pointers such as boost::shared_ptr so that
you don't have to struggle with deallocation and invalid
pointers and so on.
If the only problem is deallocation, the Boehm garbage collector
is a much simpler solution than boost::shared_ptr. But neither
it nor boost::shared_ptr can protect you from all pointer
errors---in particular, it's remarkably easy to get an invalid
pointer in C++ if you start with the address of an object with
automatic lifetime. And even with dynamically allocated
objects, the fact that the memory for the object hasn't been
freed doesn't guarantee the object's validity.

The problem with pointers is that they are a low level concept,
used to implement several different high level concepts.
Logically, you might argue that you need a different type of
smart pointer for each high level concept, but in practice, the
wrapper in many cases would be so thin that it's not worth the
bother. (Or maybe it is, for beginners. Just turning off
pointer arithmetic, for example, which probably shouldn't be
used in modern C++ unless you're implementing something like
std::vector.)

Just systematically replacing all raw pointers with
boost::shared_ptr, however, is almost guaranteed to get you into
trouble.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Oct 23 '07 #6
On 22 okt, 13:15, Markus Pitha <newsgroupsNOS...@pithax.netwrote:
Then often I have the problem that I have a method which should obtain a
non pointer variable, but in this case I only have a pointer to this
variable, and what then?
To turn a 'pointer to Something' into 'Something', you have to
dereference the pointer.
>
Let's see my actual example which leads to a "segemntation fault" or
doesn't even compile:

----------------------------------------------------

class Adjazenzmatrix
--------------------
<snip>
//This is weird. Here I want to iterate over every element of "knoten",
but....

for (int kBez = 0; kBez < groesse; kBez++) {
findKomponenten(knoten[kBez]); //LINE 178
}}

-------------------------------------------

...I get the following error message while compiling:

markus@gentoo ~/CPP-Programme/ $ g++ *.cpp -o Main `pkg-config gtkmm-2.4
--cflags --libs`
Adjazenzmatrix.cpp: In member function »void
Adjazenzmatrix::berechneEigenschaften()«:
Adjazenzmatrix.cpp:178: Fehler: ungültige Umwandlung von »Knoten*« in »int«
Adjazenzmatrix.cpp:178: Fehler: Argument 1 von »Knoten::Knoten(int)«
wird initialisiert

Which means something like:
Invalid conversion of "Knoten*" to "int.
Error: Argument 1 of Knoten::Knoten(int) will be initialized.

What does that mean?

Here is the method findKomponenten:
-------------------------------------------------
void Adjazenzmatrix::findKomponenten(Knoten k) {
The compiler complays, because you try to pass a 'Knoten*' to a
function that expects a 'Knoten' parameter. The compiler tries to
convert for you, using the Knoten constructor, but fails.
To pass a 'Knoten' object, you would have to write line 178 as:
findKomponenten(*knoten[kBez]); //LINE 178
Note that this will cause a *copy* of the relevant array element to be
passed.

<snip>
As you can see, I use a self programmed dynamically list in this class.
Now it's getting complicated for me. Later in this class, I initialize
new ListT-elements which are also "Knoten". I want to access those
elements from Adjazenzmatrix so I have sometimes already pointer with
the deep of two and then I'm not sure anymore how to handle it.
I don't know if I should return a pointer or not or as I already said,
the return values doesn't "fit" to the class which invokes the methods
of the instances because the method returns a non pointer value but in
the invoking class I have a pointer.
C++ is not a language that easily lets you fiddle about. To get a
working, moderately complex system, you need to think about the design
before you write the first line of code. This includes thinking about
how you are going to pass parameters/return values about.
And remember that C++ is very eager to make copies of things. If you
don't want a copy, you will have to explicitly use a reference or
pointer (and think about if the object you are passing will live long
enough).
I alwasy fight with such problems, so I need to get deeper into the
knowledge of handling with pointer.

Markus
Bart v Ingen Schenau

Oct 24 '07 #7
Hello again,

thanks to everyone for your answers.
I rewrote my complete program to use std::vector instead of my ListT
class and std::vector seemed to make the job. I get no errors anymore.

Markus
Oct 26 '07 #8

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

Similar topics

1
by: Emile van Sebille | last post by:
QOTW: "If we get 2.3.3c1 out in early December, we could release 2.3.3 final before the end of the year, and start 2004 with a 100% bug-free codebase <wink>." -- Tim Peters "cjOr proWe vbCould...
5
by: Bikash | last post by:
Hello, I am a specific problem in exception handling. The code snippets is attached below. void f() { char *ptr = new char(20); throw 2; }
59
by: seberino | last post by:
I've heard 2 people complain that word 'global' is confusing. Perhaps 'modulescope' or 'module' would be better? Am I the first peope to have thought of this and suggested it? Is this a...
18
by: vashwath | last post by:
Hi all, As per our coding rule, a line should not have more than 80 characters. When accessing a structure elements which are deeply nested, we are not able follow this rule. To acheive this Can...
3
by: Sai Kit Tong | last post by:
I posted for help on legacy code interface 2 days ago. Probably I didn't make it clear in my original mail. I got a couple of answers but none of them address my issues directly (See attached...
1
by: GS | last post by:
Any points of what would be the good error handling design for application? User error handling in Application_OnError and throw() new errors on conditions through the code? I'd like utlimiately to...
7
by: whitesmith | last post by:
I know that discussions of handling the user experience of those who elect not to enable JS go back years, so I'll focus on two sites that handle it in different ways. First of all, there is...
206
by: WaterWalk | last post by:
I've just read an article "Building Robust System" by Gerald Jay Sussman. The article is here: http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf In it there is a...
0
by: WebCM | last post by:
I hope you can spend some time and help me to select proper application design and programming issues. :) I'm making new version of CMS. I've been mostly theorizing about it for a recent months. ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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
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
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...
0
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...

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.