Computer Science Canada

Weird segfault behaviour

Author:  Zeroth [ 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?

Author:  DemonWasp [ 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.

Author:  Zeroth [ 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


: