-
Segmentation fault?
Hello all, I'm a beginner in C.
I want to implement a stack data structure.
typedef struct stackNode
{
int value;
struct stackNode *next;
} stackElement;
typedef stackElement *stackPtr;
stackPtr newElement(void)
{
stackPtr element;
element = (stackPtr)malloc(sizeof(stackElement));
element->next = NULL;
return(element);
}
in main function I declare it...
int main(void)
{
stackPtr tmp;
stackPtr stack = NULL;
....
tmp = newElement();
return 0;
}
why every time i try to use newElement()
it gives a runtime error (Segmentation fault,
core dumped)?
And what does the error mean?
Thanks for the help,
Ronald
-
> 1. first off, the (stackPtr) cast is not necessary (and occasionally wrong) in ANSI-C. You do not need it, if you have #included stdlib.h, and if you haven't, then you'll get a warning.
This is true for most compilers, but some will still give errors about casting from void *; not every compiler out there will allow you to leave the casting off.
-
> This is true for most compilers, but some will still give errors
> about casting from void *; not every compiler out there will
> allow you to leave the casting off
This is like saying "My program compiles without warnings... if I turn them off for the compiler! That supress errors flag is nice!"
Quzah.
-
Ok, let me get this straight...
20 seconds ago, on my last post, I was signed in.
Now, I reply to this thread, and suddenly I'm not signed in again?!
Have I ever mentioned how much I hate the timer on this board?
I thought so...
:mad: Quzah. :mad:
-
Ok, I have changed my code ...
stackPtr newElement(void)
{
stackPtr element;
element = malloc(sizeof(stackElement));
if ( element == NULL )
{
fprintf( stderr, "Out of memory" );
exit(1);
}
element->next = NULL;
return(element);
}
and alternate it with cast and no-cast with
(stackPtr in front of malloc). But still give
the seg fault error.
Any other explanation?
Thanks for the help
Ronald
-
I think it's not because of the malloc.
Just declaring
stackPtr tmp;
will give me Seg fault error.
Maybe there's something wrong with my structure?
typedef struct stackNode
{
int value;
struct stackNode *next;
} stackElement;
typedef stackElement *stackPtr;
Thanks for the help,
Ronald
-
> I think it's not because of the malloc.
> Just declaring
> stackPtr tmp;
The problem is not with this. Just declaring a variable instance does _NOT_ give you a segfault. The error is elsewhere in your program.
Defining a structure also will not give you a segfalt.
Quzah.
-
Ok,
I can't see why you are getting segmentation faults, for some reason sometimes if you put '#define MyMalloc mallc(x)' in there it fixes things, I have _NO_ idea why :/
Um, I doubt this will make any difference, but also, if you are using Linux or FreeBSD or something, you can try a program called 'gdb'. Simply type 'gdb ./PathAndOrBinaryName' then 'rrun BinaryName'. When you get the seg fault, type 'back' in the console and you will get where the error occured :)