473,770 Members | 1,779 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

qsort - Segmentation Fault

KS

Hello,

I'm writing some c++ code after a few years with Java and your help is
appreciated. I am getting a core dump on a call to qsort. Can you take
a look at the code and see if there are any obvious errors? (The
function main is at the bottom of the file.)

Code: http://www.grex.org/~kpp/cmultiknapsack.cpp

To run this file you will need http://www.grex.org/~kpp/orlib1.txt in
the same directory.

KS

Aug 14 '06 #1
6 4627
KS wrote:
I'm writing some c++ code after a few years with Java and your help is
appreciated. I am getting a core dump on a call to qsort. Can you take
a look at the code and see if there are any obvious errors? (The
function main is at the bottom of the file.)
[...]
Please follow the recommendations in FAQ 5.8.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 14 '06 #2
KS
Please follow the recommendations in FAQ 5.8.

V
Thanks. I'm using Borland C++ 5.02 on Windows and gcc on grex. Both
report the same thing. No special compiler/linker flags are used. The
message I get is a simple core dump (Segmentation fault). Its not
possible to post minimal code in this case (all parts from the
beginning to end are required for compilation and execution). The part
that causes the segmentation fault is the call to qsort (12th line in
main()).

KS

Aug 14 '06 #3
KS schrieb:
Hello,

I'm writing some c++ code after a few years with Java and your help is
appreciated. I am getting a core dump on a call to qsort. Can you take
a look at the code and see if there are any obvious errors? (The
function main is at the bottom of the file.)

Code: http://www.grex.org/~kpp/cmultiknapsack.cpp

To run this file you will need http://www.grex.org/~kpp/orlib1.txt in
the same directory.
http://www.parashift.com/c++-faq-lit...t.html#faq-5.8

Decide if you want to write C++ or C. Mixing the two languages utilize the
worst of two worlds.

For C++: Use std containers when possible and std::sort instead of qsort().
Don't new() everything. It might be necessary in Java, but its bad practice
in C++.

--
Thomas
Aug 14 '06 #4
In article <11************ *********@p79g2 000cwp.googlegr oups.com>,
kn*******@gmail .com says...
>
Hello,

I'm writing some c++ code after a few years with Java and your help is
appreciated. I am getting a core dump on a call to qsort. Can you take
a look at the code and see if there are any obvious errors? (The
function main is at the bottom of the file.)
I haven't tried to find the specific problem you're citing in the code.
Just at first glance, it has enough problems that I'd advise nearly a
complete rewrite. I'll cite only a few of the most obvious problems, and
leave it to you to clean it up enough that it's worth looking at in more
detail.
/* Globals */
int POPULATION = 10;
int NUMBER_OBJECTS = 100;
int NUMBER_CONSTRAI NTS = 5;
Commenting that these are globals is silly -- anybody who knows enough
to read the rest at all already knows these are globals.

In C and C++, all-caps names are normally reserved for macros -- these
names are misleading. Most of these probably shouldn't exist in the
first place -- in a typical case, the number of objects, constraints,
etc. should be detected from the input data. I'd use things like:

const int population = 10;
const int number_objects = 100;
const int number_constrai nts = 5;
int generateRandomN umber(int min, int max)
{
int r;
double randd = ((double)rand() / ((double)(RAND_ MAX)+(double)(1 )));
r = (int) (randd * (double)(max-min+1)) + min;
return r;
}
This manages to be both inefficient and incorrect. Personally, my
recommendation is:

int rand_lim(int limit) {
int divisor = RAND_MAX/(limit+1);
int retval;

do {
retval = rand() / divisor;
} while (retval limit);

return retval;
}

int GenerateRandomN umber(int lower, int upper) {
int range = abs(upper-lower);

return rand_lim(range) + min(lower, upper);
}

This avoids floating point, and produces numbers that are evenly
distributed within the specified range (assuming rand() produces an even
distribution in its range).
class KNode
{
private:
int * knapsack;
int value;
int * weights;
Members of a class are private by default so I'd skip the "private" tag.
Looking below, knapsack apparently has a fixed size, and is only
supposed to hold the values 0 and 1. If that's correct, I'd do something
like this:
typedef bitset<number_o bjectsknappy;

knappy knapsack;

You might also consider a vector<boolas an alternative, but offhand
the bitset looks more suitable to me. It appears that weights does hold
actual integers, so I'd define it as:

vector<intweigh ts;
public:
KNode()
{
printf("\nShoul d Not Call Default Constructor!");
}
If you don't want this to be called, declare it private, and don't
define it. This prevent code that attempts to use it from building at
all instead of building and then giving an error message at runtime.
> KNode(int * knap)
{
//printf("\nThe right constructor");
knapsack = new int [NUMBER_OBJECTS];
for(int i=0; i<NUMBER_OBJECT S; i++)
{
if(knap[i] == 1)
{
knapsack[i] = 1;
}
else if(knap[i] == 0)
{
knapsack[i] = 0;
}
else
{
printf("Invalid Knapsack passed to constructor!");
printf("i = %d, value = %d", i, knap[i]);
exit(1);
}
}
Using the definition of knapsack from above (i.e. as a bitset), this
code becomes something like:

KNode(knappy knap) : knapsack(knap) {
calculateWeight s();
calculateValue( );
crossoverType = randomCrossover ();
}

Your copy ctor isn't entirely clear. Do you really need to recalculate
the weights and value in it? It appears that it can simply copy those in
the existing one. If that's so, you can simply skip defining it at all,
as the one the compiler will produce will work fine (once you've defined
knapsack and weights properly). Likewise with operator=; in fact, the
one you have right now almost certainly does NOT do what you want -- it
does a shallow copy, so you end up with two objects pointing to the same
knapsack and weights rather than having two independent copies of those.
Right now, KNodes also leak memory -- you don't have a ctor for KNode,
so the memory it allocates in its ctor is never freed. Fortunately, when
you redefine its pointer members as container types, you no longer have
to worry about that.
KNode * mutate(KNode * node, double prob)
{
printf("Inside mutator\n");
int * knapsack = node->getKnapsack( );
int * kk = new int[NUMBER_OBJECTS];
for(int i=0; i<NUMBER_OBJECT S; i++)
{
double rand = generateDoubleR andomNumber();
if(rand < prob)
{
// invert
if(knapsack[i] == 1)
{
kk[i]=0;
}
else if(knapsack[i] == 0)
{
kk[i]=1;
}
else
{
printf("%d\n\n" , knapsack[i]);
printf("Invalid Knapsack");
exit(1);
}
}
}

KNode * nd = new KNode(kk);
return nd;
}
Using the prior definitions, this becomes something like:

KNode mutate(Knode const &node, double prob) {
knappy kk(node.knapsac k);

for (int i=0; i<node.knapsack .size(); i++) {
double random = ;
if (generateDouble RandomNumber() < prob)
kk.flip(i);
}
return KNode(kk);
}

I'd also consider re-defining this in general though -- 'mutate' sounds
like a verb -- i.e. that when you do something like "mutate(x)' it
should change the value of 'x'. Given what it really does, create_mutant
or something like that would probably be a better name.

I'll stop here with the specifics, and instead add a few general
comments: your code shows your Java background quite clearly -- in fact,
even if a C++ compiler will accept what you write, what you have is
still really more Java than C++.

My advice would be to treat the 'new' keyword as strictly forbidden, at
least for a while, until you're most accustomed to how C++ works. Right
now, you're using dynamic allocation when it's unnecessary, and leaking
memory all over everywhere. These problems should mostly evaporate if
you start to use containers from the standard library. Along with those,
you should look into using some of the standard algorithms -- for
example, you have a number of loops that could be replaced with
algorithsm such as std::accumulate .

Getting back to your original question, the problem is almost certainly
related to your (mis-)management of memory. My immediate advice would be
to ignore the existence of qsort, and use std::sort instead. With
careful use, qsort undoubtedly CAN do what you need -- but std::sort
will almost certainly do it more easily, and as a minor bonus, will
probably run quite a bit faster as well.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 14 '06 #5
In article <MP************ ************@ne ws.sunsite.dk>,
jc*****@taeus.c om says...

[ a couple of errors in editing...]
Right now, KNodes also leak memory -- you don't have a ctor for KNode,
That should be 'dtor' rather than ctor.

[ ... ]
KNode mutate(Knode const &node, double prob) {
knappy kk(node.knapsac k);

for (int i=0; i<node.knapsack .size(); i++) {
double random = ;
And this line shouldn't be there at all. There's also no real need to
use node.knapsack.s ize here -- kk.size works fine:

KNode mutate(Knode const &node, double prob) {
knappy kk(node.knapsac k);

for (int i=0; i<kk.size(); i++)
if (generateDouble RandomNumber() < prob)
kk.flip(i);
return KNode(kk);
}

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 14 '06 #6
KS
Getting back to your original question, the problem is almost certainly
related to your (mis-)management of memory. My immediate advice would be
to ignore the existence of qsort, and use std::sort instead. With
careful use, qsort undoubtedly CAN do what you need -- but std::sort
will almost certainly do it more easily, and as a minor bonus, will
probably run quite a bit faster as well.

--
Later,
Jerry.
Thanks for the detailed critique of the code. I have now switched to
STL (vector and std::sort()) and the original problem has been solved.
(Now it is complaining about bad parsing, which I can handle).

Aug 15 '06 #7

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

Similar topics

3
11445
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 () from /lib/tls/libc.so.6 It's really strange; I just call malloc() like "tmp=malloc(size);" the system gives me Segmentation fault I want to write a code to do like a dynamic array, and the code is as
5
2998
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 understood that a segmentation fault can occur whenever I declare a pointer and I leave it un-initialized. So I thought the problem here is with the (const char *)s in the stuct flightData (please note that I get the same fault declaring as char * the...
18
26121
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)? Thanks.
27
3367
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! #include <stdlib.h> #include <stdio.h> typedef struct _node_t {
7
5880
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 testcases we experiance Segmentation fault from the python libraries. If i know how to handle the exception for Segmentation fault , it will help me complete the run on any testcase , even if i experiance Seg Fault due to any one or many functions in...
3
5187
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 from 10g release2 PHP is configured with the following parameters './configure' '--prefix=/opt/oracle/php' '--with-apxs=/opt/oracle/apache/bin/apxs' '--with-config-file-path=/opt/oracle/apache/conf' '--enable-safe-mode' '--enable-session'...
17
1836
by: arne.muller | last post by:
Hello, I just had to find out that a program that runs fine under linux and True64 alpha crashed with a segmentation fault under SunOS 5.8. I drilled down and it appears that if the sun qsort gets a vector in which all elements are equivalent, my comparsion function raises SEGSEGV. The problem seems to be that all elements are the same sun qsort always passes NULL as the first element to the comparsion function....
4
15500
by: gallows | last post by:
I've tried to use C qsort() on an object derivate by std::vector, but it doesn't work. I've the follow structure: struct Item { std::string name; int number; }
6
5043
by: DanielJohnson | last post by:
int main() { printf("\n Hello World"); main; return 0; } This program terminate just after one loop while the second program goes on infinitely untill segmentation fault (core dumped) on gcc. The only difference is that in first I only call "main" and in second call
0
9617
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10037
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9904
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8931
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7456
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6710
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4007
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 we have to send another system
2
3609
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.