Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Weird segfault behaviour
Index -> Programming, C -> C Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Zeroth




PostPosted: Sun Apr 19, 2009 11:33 am   Post subject: Weird segfault behaviour

Okay, so I was really bored, decided to learn how the radix sort works.

I made this program, and I run into segfault behaviour when MAXSIZE is 218100 or greater. And it seems to happen randomly. What the heck is going on?



sort.c
 Description:

Download
 Filename:  sort.c
 Filesize:  2.52 KB
 Downloaded:  178 Time(s)

Sponsor
Sponsor
Sponsor
sponsor
DemonWasp




PostPosted: Sun Apr 19, 2009 3:58 pm   Post subject: RE:Weird segfault behaviour

You appear to be allocating the array ret[] on the stack (as opposed to on the heap) and then returning a pointer to it. When the stack unwinds with the return, your pointer is no longer valid and may point to pretty well anything (the original array, a new version of it, some garbage in RAM, or some entirely unrelated stuff in a new method, etc).

If you really need to return an integer array, you need to allocate it as a pointer:

code:

int * ret = new int[size];


This analysis was done by gcc and not by me actually looking at your algorithm, so there may be other errors.
Zeroth




PostPosted: Sun Apr 19, 2009 4:10 pm   Post subject: Re: Weird segfault behaviour

Yeah, I've got it solved. Basically stack overflow issues. I changed it to an iterative form instead of recursive, used malloc for all the arrays, and it does up to a million integers and sorts them in less than a second. Smile
Display posts from previous:   
   Index -> Programming, C -> C Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: