473,545 Members | 1,977 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why does this segfault??

could someone please have a look at this and tell me why it segfaults. i
am confused as all hell!

stringman.h
void load_string(cha r *newString);
char * remove_string() ;
char * remove_upper_st ring();
char * remove_lower_st ring();

(i havent written the removes yet);

then the source
stringman.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* fundamental structure definition */
typedef struct list_member{
char *m_data;
struct list_member *m_next;
} MEMBER;

// initalise head pointer
MEMBER *headptr;

void load_string(cha r *newString)
{
printf("checkpo int1");
//create new list_member for new string
MEMBER *newmem, *curr;
printf("checkpo int2");
if((newmem=(MEM BER *)malloc(sizeof (MEMBER)))==(ME MBER *)0)
{
printf("checkpo int2a");
fprintf(stderr, "out of memory in new_member\n");
}
else
{
printf("checkpo int2b");
/* create memory to copy data into*/
newmem->m_data = (char *)malloc(strlen (newString)+1);
printf("checkpo int2c");
/* copy data into structure, assuming it is a string */
strcpy(newmem->m_data, newString);
printf("checkpo int2d");
/* set the pointer in the structure to null */
newmem->m_next = (MEMBER *)0;
}
printf("checkpo int3");
// set current to 1st list_member
curr = headptr;
printf("checkpo int4");
// check if list is empty
if(curr->m_next == (MEMBER *)0)
{
printf("checkpo int4a");
headptr->m_next = newmem;
}
else
{
// go to the end of the list
printf("checkpo int4b");
while(curr->m_next != (MEMBER *)0)
{
printf("checkpo int4c");
curr = curr->m_next;
}
printf("checkpo int5");
// change last ptr to point to current
curr->m_next = newmem;
printf("checkpo int6");
}
}
then the testing program
test.c
#include "stringman. h"

int main()
{
char *test = "test1", *test2= "test2", *test3 =
"12345678910111 213141516171819 202122232425262 728293031323334 3536373839404
142434445464748 495051525354555 657585960616263 646566676869707 1727374757677
787980818283848 586878889909192 939495969798991 001011021031041 0510610710810
911011111211311 4115116117";
printf("\n test = %s\n",test);
printf("\n test2 = %s\n",test2);
printf("\n test3 = %s\n",test3);
load_string(tes t);
printf("load1ok ");
load_string(tes t2);
printf("load2ok ");
load_string(tes t3);
printf("load3ok ");
printf("all loaded ok so it looks like");
}
and then the output
$ ./test

test = test1

test2 = test2

test3 =
123456789101112 131415161718192 021222324252627 282930313233343 53637383940
414243444546474 849505152535455 565758596061626 364656667686970 7172737475767
7787980
818283848586878 889909192939495 969798991001011 021031041051061 0710810911011
1112113
114115116117
Segmentation fault (core dumped)

as you can see, it seams to dump before any of the code in load_string()
is run.
im fucking confused as hell. like how can it dump before printing
checkpoint 1, its the 1st thing in string_load() so how is it dumping
before that...
Nov 13 '05 #1
6 2191
deejaybags wrote:
could someone please have a look at this and tell me why it segfaults. i
am confused as all hell!
In general, posting this much code is a Bad Idea. In the future,
limit your code to the smallest compilable snippet that exhibits the
problem (which has the added beneficial side effect of often
pointing you to the error in the process).

But OK, here goes...

stringman.h
void load_string(cha r *newString);
char * remove_string() ;
char * remove_upper_st ring();
char * remove_lower_st ring();

(i havent written the removes yet);

then the source
stringman.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* fundamental structure definition */
typedef struct list_member{
char *m_data;
struct list_member *m_next;
} MEMBER;

// initalise head pointer
MEMBER *headptr;

void load_string(cha r *newString)
{
printf("checkpo int1");
//create new list_member for new string
MEMBER *newmem, *curr;
printf("checkpo int2");
if((newmem=(MEM BER *)malloc(sizeof (MEMBER)))==(ME MBER *)0)
Don't cast the return value of malloc(). It's unnecessary and can
hide other errors (like, for example, failing to include <stdlib.h>).

Also, it is better to use:
if ((newmem = malloc( sizeof *newmem) == NULL)

{
printf("checkpo int2a");
fprintf(stderr, "out of memory in new_member\n");
}
else
{
printf("checkpo int2b");
/* create memory to copy data into*/
newmem->m_data = (char *)malloc(strlen (newString)+1);
printf("checkpo int2c");
/* copy data into structure, assuming it is a string */
strcpy(newmem->m_data, newString);
printf("checkpo int2d");
/* set the pointer in the structure to null */
newmem->m_next = (MEMBER *)0;
}
printf("checkpo int3");
// set current to 1st list_member
curr = headptr;
Ding ding ding...
What's the value of `headptr' here?
[Hint: you neither initialize it nor assign to it]
printf("checkpo int4");
// check if list is empty
if(curr->m_next == (MEMBER *)0)
{
printf("checkpo int4a");
headptr->m_next = newmem;
}
else
{
// go to the end of the list
printf("checkpo int4b");
while(curr->m_next != (MEMBER *)0)
{
printf("checkpo int4c");
curr = curr->m_next;
}
printf("checkpo int5");
// change last ptr to point to current
curr->m_next = newmem;
printf("checkpo int6");
}
}
then the testing program
test.c
#include "stringman. h"

int main()
{
char *test = "test1", *test2= "test2", *test3 =
"12345678910111 213141516171819 202122232425262 728293031323334 3536373839404
142434445464748 495051525354555 657585960616263 646566676869707 1727374757677
787980818283848 586878889909192 939495969798991 001011021031041 0510610710810
911011111211311 4115116117";
printf("\n test = %s\n",test);
printf("\n test2 = %s\n",test2);
printf("\n test3 = %s\n",test3);
load_string(tes t);
printf("load1ok ");
load_string(tes t2);
printf("load2ok ");
load_string(tes t3);
printf("load3ok ");
printf("all loaded ok so it looks like");
}
and then the output
$ ./test

test = test1

test2 = test2

test3 =
123456789101112 131415161718192 021222324252627 282930313233343 53637383940
414243444546474 849505152535455 565758596061626 364656667686970 7172737475767
7787980
818283848586878 889909192939495 969798991001011 021031041051061 0710810911011
1112113
114115116117
Segmentation fault (core dumped)

as you can see, it seams to dump before any of the code in load_string()
is run.
im fucking confused as hell. like how can it dump before printing
checkpoint 1, its the 1st thing in string_load() so how is it dumping
before that...


It isn't. The stream stdout is typically buffered, hence output does
not appear unless you provide a newline character or explicitly
flush the stream.

HTH,
--ag
--
Artie Gold -- Austin, Texas

Nov 13 '05 #2
deejaybags <de********@yah oo.com> wrote:
could someone please have a look at this and tell me why it segfaults. i
am confused as all hell!

stringman.h
void load_string(cha r *newString);
char * remove_string() ;
char * remove_upper_st ring();
char * remove_lower_st ring();

(i havent written the removes yet);

then the source
stringman.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* fundamental structure definition */
typedef struct list_member{
char *m_data;
struct list_member *m_next;
} MEMBER;

// initalise head pointer
MEMBER *headptr;

void load_string(cha r *newString)
{
printf("checkpo int1");
//create new list_member for new string
MEMBER *newmem, *curr;
printf("checkpo int2");
if((newmem=(MEM BER *)malloc(sizeof (MEMBER)))==(ME MBER *)0) Better:
if ( ( newmem = malloc( sizeof *newmem ) ) == NULL )

But that's not the problem.
{
printf("checkpo int2a");
fprintf(stderr, "out of memory in new_member\n");
}
else
{
printf("checkpo int2b");
/* create memory to copy data into*/
newmem->m_data = (char *)malloc(strlen (newString)+1); Better:
newmem->m_data = malloc( strlen( newString ) + 1 );

You failed to check malloc()s return value.
But that's not the problem.
printf("checkpo int2c");
/* copy data into structure, assuming it is a string */
strcpy(newmem->m_data, newString);
printf("checkpo int2d");
/* set the pointer in the structure to null */
newmem->m_next = (MEMBER *)0; Better:
newmem->m_next = NULL;
But that's still not the problem.
}
printf("checkpo int3");
// set current to 1st list_member
curr = headptr; Caaaaarefully.. .
printf("checkpo int4");
// check if list is empty
if(curr->m_next == (MEMBER *)0) Gotcha!!!
You failed to allocate some memory for headptr (and therefore curr)
to point to, so curr->m_next invokes dreaded undefined behaviour. {
printf("checkpo int4a");
headptr->m_next = newmem;
} Change the above to:

// check if list is empty
if( headptr == NULL )
{
printf("checkpo int4a");
headptr = newmem;
} else
{
// go to the end of the list
printf("checkpo int4b");
while(curr->m_next != (MEMBER *)0)
{
printf("checkpo int4c");
curr = curr->m_next;
} That's a very inefficient way to do it. Maybe you want to maintain a
pointer to your last element, or just insert at the head of the list.
printf("checkpo int5");
// change last ptr to point to current
curr->m_next = newmem;
printf("checkpo int6");
}
}
then the testing program
test.c
#include "stringman. h"

int main()
{
char *test = "test1", *test2= "test2", *test3 =
"1234567891011 121314151617181 920212223242526 272829303132333 43536373839404
14243444546474 849505152535455 565758596061626 364656667686970 71727374757677
78798081828384 858687888990919 293949596979899 100101102103104 10510610710810
91101111121131 14115116117";
printf("\n test = %s\n",test);
printf("\n test2 = %s\n",test2);
printf("\n test3 = %s\n",test3);
load_string(tes t);
printf("load1ok ");
load_string(tes t2);
printf("load2ok ");
load_string(tes t3);
printf("load3ok ");
printf("all loaded ok so it looks like");
}
and then the output
$ ./test

test = test1

test2 = test2

test3 =
12345678910111 213141516171819 202122232425262 728293031323334 353637383940
41424344454647 484950515253545 556575859606162 636465666768697 07172737475767
7787980
81828384858687 888990919293949 596979899100101 102103104105106 10710810911011
1112113
114115116117
Segmentation fault (core dumped)

as you can see, it seams to dump before any of the code in load_string()
is run. Right, it /seems/ so, but: if you just had appended a '\n' to the
strings you print at your checkpoints (or did a fflush(stderr) after
each printf), you would have noticed that your program runs fine till
"checkpoint 4" is printed, and then segfaults - reason given above.

im fucking confused as hell. like how can it dump before printing
checkpoint 1, its the 1st thing in string_load() so how is it dumping
before that...


Relax, we've all gone through it. :)
Some more suggestions:
- don't use C99 single line comments when posting code here: it may
result in broken code if a line is wrapped by the newsreader, and
some people use compilers not capable to deal with //-comments

- do not cast the return value of malloc: you gain nothing but hiding
the fact you eventually forgot to #include <stdlib.h>

- just use NULL insted of (some_type *)0, that's what it is made for

- it's better style to write

my_ptr = malloc( sizeof *my_ptr * NUMBER );

instead of

my_ptr = malloc( sizeof (my_ptr_type) *NUMBER );

If the type of my_ptr ever changes in the future, you do not have to
go through your code and fix all the malloc()s.

Regards

Irrwahn
--
I can't see it from here, but it looks good to me.
Nov 13 '05 #3
nrk
deejaybags wrote:
could someone please have a look at this and tell me why it segfaults. i
am confused as all hell!

stringman.h
void load_string(cha r *newString);
char * remove_string() ;
char * remove_upper_st ring();
char * remove_lower_st ring();

(i havent written the removes yet);

then the source
stringman.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* fundamental structure definition */
typedef struct list_member{
char *m_data;
struct list_member *m_next;
} MEMBER;

// initalise head pointer
MEMBER *headptr;

headptr is initialized alright. It's initialized to NULL, and
de-referencing it will produce undefined behavior (one manifestation of
which can be a "segfault") .
void load_string(cha r *newString)
{
printf("checkpo int1"); Read your C book carefully. The output stream can be line-buffered or
fully-buffered. Change this (and all your other printfs) to add a '\n' at
the end:
printf("checkpo int1\n");
If you're paranoid, add a fflush(stdout); . Then you should see atleast some
of your printf's showing up.
//create new list_member for new string
MEMBER *newmem, *curr;
printf("checkpo int2");
if((newmem=(MEM BER *)malloc(sizeof (MEMBER)))==(ME MBER *)0) Style Point: Way too much going on in one line. This style of coding might
make debugging difficult. Why not write:

newmem = malloc(sizeof *newmem);
if ( newmem == NULL )

Notice how the malloc has been done. This is the clc preferred way. Do
*NOT* cast the return of malloc. Use the pointer to be allocated to
determine the size for allocation, if possible.
{
printf("checkpo int2a");
fprintf(stderr, "out of memory in new_member\n");
}
else
{
printf("checkpo int2b");
/* create memory to copy data into*/
newmem->m_data = (char *)malloc(strlen (newString)+1); newmem->m_data = malloc(strlen(n ewString) + 1);

How about checking the return of that malloc as well? In the worst case,
atleast put an:
assert(ptr != NULL);
after your mallocs.
printf("checkpo int2c");
/* copy data into structure, assuming it is a string */
strcpy(newmem->m_data, newString);
printf("checkpo int2d");
/* set the pointer in the structure to null */
newmem->m_next = (MEMBER *)0; What's wrong with:
newmem->m_next = NULL;
}
printf("checkpo int3");
// set current to 1st list_member
curr = headptr;
Notice that headptr is still NULL and hasn't been initialized to be a valid
pointer to a MEMBER structure. Perhaps you missed:
if ( headptr == NULL ) {
headptr = newmem;
return;
}

That will make a list where the head is simply the first node of the list.

OTOH, if you wanted a linked list with a dummy head that is always present,
then you must allocate headptr as in:

MEMBER dummy;
MEMBER *headptr = &dummy;

instead of the declaration you have for headptr now.
printf("checkpo int4");
// check if list is empty
if(curr->m_next == (MEMBER *)0)
{
printf("checkpo int4a");
headptr->m_next = newmem;
}
else
{
// go to the end of the list
printf("checkpo int4b");
while(curr->m_next != (MEMBER *)0)
{
printf("checkpo int4c");
curr = curr->m_next;
}
printf("checkpo int5");
// change last ptr to point to current
curr->m_next = newmem;
printf("checkpo int6");
}
}
then the testing program
test.c
#include "stringman. h"

int main()
{
char *test = "test1", *test2= "test2", *test3 =
"12345678910111 213141516171819 202122232425262 728293031323334 3536373839404
142434445464748 495051525354555 657585960616263 646566676869707 1727374757677
787980818283848 586878889909192 939495969798991 001011021031041 0510610710810
911011111211311 4115116117";
printf("\n test = %s\n",test);
printf("\n test2 = %s\n",test2);
printf("\n test3 = %s\n",test3);
load_string(tes t);
printf("load1ok ");
load_string(tes t2);
printf("load2ok ");
load_string(tes t3);
printf("load3ok ");
printf("all loaded ok so it looks like");


return 0;

Turn up the warning levels in your compiler.

<OT>If you're using gcc, -Wall -ansi -O atleast.</OT>

Additional Style Point:
- Learn to intend your code consistently and in a manner that makes it easy
to read. If you lack ideas, turn to good C books or look at examples being
posted by the regulars here.

HTH,
nrk.
Nov 13 '05 #4
You guys are the sikest!!!! thanks heaps *punches self in head* had a
feeling the headptr was the prob but couldnt see the error with my
newbie brain! thanks again!! your all the best!!!!!!!!!!

peace
eye-bags-won
Nov 13 '05 #5
On Thu, 11 Sep 2003 22:40:31 UTC, nrk <nr*******@hotm ail.com> wrote:
if((newmem=(MEM BER *)malloc(sizeof (MEMBER)))==(ME MBER *)0) Style Point: Way too much going on in one line. This style of coding might
make debugging difficult. Why not write:


Not a style point, a point to let the compier give a diagnostic when
you've forgotten to include stdlib.h. It helps you to debug your code
as it checks that you have the prototype known.

Never use a function that returns anything except int without the
prototype known.
newmem = malloc(sizeof *newmem);
if ( newmem == NULL )

Notice how the malloc has been done. This is the clc preferred way. Do
*NOT* cast the return of malloc. Use the pointer to be allocated to
determine the size for allocation, if possible.
{
printf("checkpo int2a");
fprintf(stderr, "out of memory in new_member\n");
}
else
{
printf("checkpo int2b");
/* create memory to copy data into*/
newmem->m_data = (char *)malloc(strlen (newString)+1);

newmem->m_data = malloc(strlen(n ewString) + 1);

How about checking the return of that malloc as well? In the worst case,
atleast put an:
assert(ptr != NULL);


Never use assert to check data. assert is a debug function that will
either kill your program or even not active in productive code because
the compiler has the rights to eliminate it when not transating for
DEBUG is done.
assert is good to check for programming errors, but never for data
errors. a fail on lack of memory is mostenly not a cause the program
has to fail, it has at least to cleanup something (cleanup internal
data, save something to disk....) instead to break immediately with a
message the user does know about or interested on.
--
Tschau/Bye
Herbert

eComStation 1.1 Deutsch Beta ist verügbar
Nov 13 '05 #6
"The Real OS/2 Guy" <os****@pc-rosenau.de> wrote:

<SNIP>
Never use a function that returns anything except int without the
prototype known.


Never use any function without a prototype in scope.

<SNIP>

--
do not write: void main(...)
do not use gets()
do not cast the return value of malloc()
do not fflush( stdin )
read the c.l.c-faq: http://www.eskimo.com/~scs/C-faq/top.html
Nov 13 '05 #7

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

Similar topics

6
3004
by: Juho Saarikko | last post by:
The program attached to this message makes the Python interpreter segfault randomly. I have tried both Python 2.2 which came with Debian Stable, and self-compiled Python 2.3.3 (newest I could find on www.python.org, compiled with default options (./configure && make). I'm using the pyPgSQL plugin to connect to a PostGreSQL database, and have...
6
1975
by: Stefan Behnel | last post by:
Hi! In Python 2.4b3, the deque is causing a segfault on two different machines I tested on. With deque, my program runs fine for a while (at least some tens of seconds up to minutes) and then suddenly segfaults. I'm sorry I can't tell exactly when, but I'm running an application that uses a few hundred deques where elements are...
4
1877
by: Jim Strathmeyer | last post by:
Under what circumstances would closing a istream object (such as 'in.close()') SEGFAULT?
4
3488
by: William Payne | last post by:
Hello, I was under the impression that if I made a class Foo and if I didn't specify a copy constructor I would get one anyway that simply assigns the member variables (and that won't work for dynamically allocated member variables). Anyway, I have a program that segfaults without a copy constructor but if I add an empty one, the segfault is...
4
3097
by: Ovid | last post by:
Hi all, I'm having a problem trying to create a 2D array whose dimensions are determined at runtime. Below my signoff is a minimal test case that hopefully demonstrates what I'm trying to do. Unfortunately, this segfaults. The output is the following: $ gcc -Wall -c arrays.c $ gcc -o arrays arrays.o $ ./arrays
28
5693
by: lovecreatesbeauty | last post by:
Besides printing out for example " a.out: p113.c:8: main: Assertion `0' failed. Aborted " and a switch option NDEBUG, what other benefits does assert() provide in any scope of designing, debugging/coding and/or testing? Do you prefer the if statement of the language to the assert MACRO of the precompiler?
3
2293
by: kj | last post by:
I am trying to diagnose a bug in my code, but I can't understand what's going on. I've narrowed things down to this: I have a function, say foo, whose signature looks something like: int foo( int w, int x, int y, int z, my_struct **results ) During its execution, foo initializes *results using calloc: ( *results ) = calloc( w+1,...
14
4944
by: Donn Ingle | last post by:
Yo, An app of mine relies on PIL. When PIL hits a certain problem font (for unknown reasons as of now) it tends to segfault and no amount of try/except will keep my wxPython app alive. My first thought is to start the app from a bash script that will check the return value of my wxPython app and could then launch a new app to help the user...
12
1820
by: Philipp.Weissenbacher | last post by:
Hi all! This is most certainly a total newbie question, but why doesn't the following code cause a segfault? void insertion_sort(int a, int length) { int i; for (i=0; i < length; i++) { int j, v = a;
0
7478
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...
0
7410
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7668
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7923
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
5984
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...
1
5343
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...
0
3466
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...
0
3448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
722
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.