473,811 Members | 3,424 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HELP!!

Here is a code I am writing. I keep geting segmentation fault.
I'm not sure what i'm doing wrong.
Can you explain it to me in PLAIN ENGLISH??

void ReadString (char *filename, int *lengthPtr, char *textFilePtr)
{
FILE *ifp;
char *text;
char txtFile[FILELENGTH];

char c;
int x = 0, y = 0, items;

text = txtFile;

printf ("Enter the name of the file to analyze : ");
fgets (filename, FILES, stdin);

printf ("%s", filename);

ifp = fopen(filename, "r");

text = malloc(FILELENG TH * sizeof(char)); **I keep
getting Segmentation fault here**

if(ifp == NULL)
{
fprintf (stderr, "Error opening file\n");
exit (-2);
}

while (fscanf (ifp, "%c", &c)!= EOF)
{
sprintf (txtFile, "%c", c);
y++;
}

for (x = 0; x < FILELENGTH; x++);
{
printf ("%c", txtFile[x]);
}

fclose (ifp);
}

Nov 5 '06 #1
5 1529
to********@gmai l.com wrote:
Here is a code I am writing. I keep geting segmentation fault.
I'm not sure what i'm doing wrong.
Can you explain it to me in PLAIN ENGLISH??
char txtFile[FILELENGTH];

text = malloc(FILELENG TH * sizeof(char)); **I keep
getting Segmentation fault here**
Well, you didn't define FILELENGTH for us, for one thing.

How do you know your segfault is exactly here? Did you single-step
through this in your debugger?

Nov 5 '06 #2
to********@gmai l.com writes:
Here is a code I am writing. I keep geting segmentation fault.
I'm not sure what i'm doing wrong.
Can you explain it to me in PLAIN ENGLISH??
You didn't show us a complete program, so we can only offer limited
help. We can't see the definitions of FILELENGTH and FILES, and we
have no idea what arguments you're passing to ReadString.
void ReadString (char *filename, int *lengthPtr, char *textFilePtr)
{
FILE *ifp;
char *text;
char txtFile[FILELENGTH];

char c;
int x = 0, y = 0, items;

text = txtFile;
Here you make text point to the beginning of the aray txtFile ...
printf ("Enter the name of the file to analyze : ");
fgets (filename, FILES, stdin);
This will fail (invoke undefined behavior) if filename doesn't point
to an array of sufficient size. You're implicitly requiring the
caller to ensure that filename points to such an array; we can't tell
whether it does so. It looks like FILES is the size in bytes of the
array that filename points to; if so, FILES is a misleading name.
printf ("%s", filename);

ifp = fopen(filename, "r");

text = malloc(FILELENG TH * sizeof(char)); **I keep
getting Segmentation fault here**
.... and here you overwrite the value of text. Reconsider your design.

How do you know that this is where the segmentation fault occurs?

sizeof(char) is 1 by definition. Change the line to either
text = malloc(FILELENG TH * sizeof *txt);
or, if text is always going to be a character pointer:
text = malloc(FILELENG TH);

malloc() returns a null pointer to indicate that the allocation
failed. *Always* check for this. (Anyone who tells you that it's
sometimes not necessary is wrong.)

If malloc() actually dies with a segmentation fault rather than
reporting a failure by returning a null pointer value, then chances
are the error is somewhere else in your program. You may have done
something else that invoked undefined behavior and messed up the
internal data structures used by malloc() and free(). This is part of
the reason why we need to see a complete, self-contained program that
exhibits the problem. If you knew where the probelm is, you wouldn't
need to ask us for help; since you don't know, you can't be sure that
the code fragment you've shown us is what's actually causing the
problem.
if(ifp == NULL)
{
fprintf (stderr, "Error opening file\n");
exit (-2);
}
I'm glad to see you're checking whether fopen() failed. As a matter
of style, I'd do so immediately after the call; if it fails, there's
no point in doing the malloc() call.

exit(-2) is not portable. The only portable arguments to exit() are
0, EXIT_SUCCESS, and EXIT_FAILURE. In this case, you want
exit(EXIT_FAILU RE). (Better yet, this function should probably use
its result to report the error to its caller rather than killing the
entire program.)
while (fscanf (ifp, "%c", &c)!= EOF)
{
sprintf (txtFile, "%c", c);
y++;
}

for (x = 0; x < FILELENGTH; x++);
{
printf ("%c", txtFile[x]);
}
fscanf(), sprintf(), and printf() are overkill here. In the fscanf()
call, you're just reading a single character at a time; just use
fgetc(). The sprintf() call writes/assigns as single character into
txtFile. Furthermore, it repeatedly assigns successive characters to
the same location; is that what you want? The printf() call can be
replaced with a simpler putchar() call.
fclose (ifp);
}
--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 5 '06 #3
to********@gmai l.com wrote:
Here is a code I am writing. I keep geting segmentation fault.
I'm not sure what i'm doing wrong.
Can you explain it to me in PLAIN ENGLISH??
void ReadString (char *filename, int *lengthPtr, char *textFilePtr)
What are 'lengthPtr' and 'textFilePtr' for? They aren't used anywhere
in this function.
{
FILE *ifp;
char *text;
char txtFile[FILELENGTH];
Where's FILELENGTH defined (and what to)?
char c;
int x = 0, y = 0, items;
What's 'items' good for? It's never used.
text = txtFile;
printf ("Enter the name of the file to analyze : ");
fgets (filename, FILES, stdin);
Where is FILES defined (and what to)? Is what 'filename' is pointing
to memory you "own" (i.e. it's either an array of chars you defined
in the caller or is memeory you received from malloc() or friends)
and has it at least room for FILES characters?

Are you aware that, if the file name isn't longer than (FILES - 2),
there's going to be a trailing newline character, which rather likely
isn't in the name of the file you want to open?
printf ("%s", filename);
ifp = fopen(filename, "r");
text = malloc(FILELENG TH * sizeof(char)); **I keep
getting Segmentation fault here**
If you get a segentation fault here then you must have had some error
when dealing with memory somewhere else in your program, probably
accidentally overwriting some of the bookkeeping information the
malloc()-family of functions needs to store. One possible place is
where you use fgets() above (if 'filename' isn't pointing to memory
large enough to hold FILES characters - but it also could be
happening in some other part of the program you're not showing.
And debugging something one can't see is a very difficult task;-)

Moreover, why made you 'text' first point to the 'txtFile' array and
now suddenly assign a different value to it? Moreover, what's the
malloc() good for at all? The 'text' variable is never used in the
following, so you simply can delete this line - all you do here is
create a memory leak since you don't even bother to free() the memory
later on.
if(ifp == NULL)
{
fprintf (stderr, "Error opening file\n");
exit (-2);
}
while (fscanf (ifp, "%c", &c)!= EOF)
{
sprintf (txtFile, "%c", c);
Do you really want to overwrite the first character of the 'txtFile'
array again and again? I have some inkling that you actually meant
to write

sprintf( txtFile + y, "%c", c);

But then you need to make sure that you never try to read more than
FILELENGTH characters from the file, even if the file is longer
than that...
y++;
I would recommend to use variable names that make a bit more sense,
here e.g. 'read_count' would help to make things easier to under-
stand.
}
for (x = 0; x < FILELENGTH; x++);
{
printf ("%c", txtFile[x]);
With your version (i.e. using only the first element of the
'txtFile' array) everything beside the first character you print
out will be garbage. But even if you correct that as pointed out
above and the number of chars you could read from the file was
less than FILELENGTH chars then you will still output garbage if
'x' beomes equal or larger than 'y'
}
fclose (ifp);
}
The whole function looks like you have started with something that
didn't work and then you went on fiddling with the code without
understanding why it didn't work. Now it's in a state that there's
one strange thing after another and it's going to be hard to untangle
the mess. I would recommend that you just comment it out, take a
deep breath, write down (in words) exactly what the function is
supposed to do and then start again from scratch, not looking at
what you already have written. Also write a minimal program that
just calls your function, nothing else, so you can test it without
being led astray by possible errors in other parts of the program.
If this new version doesn't work don't go messing around with it
more or less randomly but come back here and let's have a look
(and also post what you wrote down the function should do and the
short program you embedded it in to test it).

Best regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Nov 5 '06 #4
On 5 Nov 2006 12:12:54 -0800, in comp.lang.c , to********@gmai l.com
wrote:
char *text;
char txtFile[FILELENGTH];
here you create a pointer and an array.
text = txtFile;
here you point the pointer AT the array.
printf ("Enter the name of the file to analyze : ");
fgets (filename, FILES, stdin);
here you read something into "filename". You don't check for overflow.
ifp = fopen(filename, "r");
.... nor do you check that you could open the file.
>
text = malloc(FILELENG TH * sizeof(char)); **I keep
getting Segmentation fault here**
here you throw away your previous assignment to text, and attempt to
malloc some memory. Other than the needless sizeof(char) [ char always
has size one, so you don't need that] this looks ok.

I expect the bug is somewhere else, your memory has already been
corrupted. My guess would be that filename is not large enough, or you
didn't allocatn any memory for it.
if(ifp == NULL)
why not do this BEFORE allocating memory?
while (fscanf (ifp, "%c", &c)!= EOF)
{
sprintf (txtFile, "%c", c);
this repeatedy overwrites the first character of txtFile.
for (x = 0; x < FILELENGTH; x++);
{
printf ("%c", txtFile[x]);
but here you try to print out all of them.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Nov 5 '06 #5
to********@gmai l.com wrote:
void ReadString (char *filename, int *lengthPtr, char *textFilePtr)
{
FILE *ifp;
char *text;
char txtFile[FILELENGTH];
char c;
int x = 0, y = 0, items;
text = txtFile;
printf ("Enter the name of the file to analyze : ");
fgets (filename, FILES, stdin);
I do hope that FILES is something reasonable.
printf ("%s", filename);
ifp = fopen(filename, "r");
text = malloc(FILELENG TH * sizeof(char)); **I keep
getting Segmentation fault here**
1) sizeof char is always 1; no need to obfuscate things here. At
least consider

text = malloc( FILELENGTH * sizeof *text );

2) Segmentation faults in malloc() are usually a good indication that
you have done something wrong elsewhere in your program, including
such things as freeing a pointer twice. If you can post a complete
(!) program that demonstrates the problem, we might be able to find it
for your. (Make that a SMALL complete program.)

3) What if malloc() fails and returns a null pointer? (hint: Checking
is a good idea.)

4) The fact that you're assigning text a malloc()'ed value after
assigning text to a character array (txtFile) suggests that you are
either misunderstandin g something or didn't post your actual code.
if(ifp == NULL)
{
fprintf (stderr, "Error opening file\n");
exit (-2);
}
Why not check before you do call malloc()? It won't matter on a
reasonable implementation, but there's no reason not to avoid malloc()
if it makes sense to do so.
while (fscanf (ifp, "%c", &c)!= EOF)
Whoa! Why not use fgetc()?
{
sprintf (txtFile, "%c", c);
Or, possibly better yet, fgets()?
}
for (x = 0; x < FILELENGTH; x++);
{
printf ("%c", txtFile[x]);
If you can't trust txtFile to be a string you can simply print with
puts() or somesuch, or at least not character-by-character, perhaps
you should open your file in binary mode.
}
fclose (ifp);
}
--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gma il.com | don't, I need to know. Flames welcome.
Nov 6 '06 #6

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

Similar topics

21
6567
by: Dave | last post by:
After following Microsofts admonition to reformat my system before doing a final compilation of my app I got many warnings/errors upon compiling an rtf file created in word. I used the Help Workshop program: hcw.exe that's included with Visual Basic. This exact same file compiled perfectly with no notes, warnings or errors prior to reformatting my system. Prior to the reformatting, I copied the help.rtf file onto a CD and checked the box to...
9
4420
by: Tom | last post by:
A question for gui application programmers. . . I 've got some GUI programs, written in Python/wxPython, and I've got a help button and a help menu item. Also, I've got a compiled file made with the microsoft HTML workshop utility, lets call it c:\path\help.chm. My question is how do you launch it from the GUI? What logic do I put behind the "help" button, in other words. I thought it would be os.spawnv(os.P_DETACH,...
6
4360
by: wukexin | last post by:
Help me, good men. I find mang books that introduce bit "mang header files",they talk too bit,in fact it is my too fool, I don't learn it, I have do a test program, but I have no correct doing result in any way. Who can help me, I thank you very very much. list.cpp(main program) //-------------------------------------------------------------------------- - #pragma hdrstop #pragma argsused
3
3370
by: Colin J. Williams | last post by:
Python advertises some basic service: C:\Python24>python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> With numarray, help gives unhelpful responses:
7
5398
by: Corepaul | last post by:
Missing Help Files When I enter "recordset" as the keyword and search the Visual Basic Help index, I get many topics of interest in the resulting list. But there isn't any information available from clicking on many of the available topics (mostly methods but some properties are also unavailable). This same problem occurs with many, if not most, keywords. Is there any way I can activate these "missing" help topics? HELP!
5
3292
by: Steve | last post by:
I have written a help file (chm) for a DLL and referenced it using Help.ShowHelp My expectation is that a developer using my DLL would be able to access this help file during his development time using "F1" help within the VB IDE. Is this expectation achievable In trying to test my help file in the IDE, I have a solution with 2 projects: the DLL and a tester. VB does not look for my help file; instead, it looks for path to my source code...
8
3241
by: Mark | last post by:
I have loaded Visual Studio .net on my home computer and my laptop, but my home computer has an abbreviated help screen not 2% of the help on my laptop. All the settings look the same on both including search the internet for help, but the help is worthless. Any ideas?
10
3375
by: JonathanOrlev | last post by:
Hello everybody, I wrote this comment in another message of mine, but decided to post it again as a standalone message. I think that Microsoft's Office 2003 help system is horrible, probably the worst I ever seen. I almost cannot find anything I need, including things I
1
6142
by: trunxnirvana007 | last post by:
'UPGRADE_WARNING: Array has a new behavior. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"' 'UPGRADE_WARNING: Couldn't resolve default property of object Label. Click for more: 'ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' Label = New Object(){Box1, Box2, Box3, Box4, Box5, Box6, Box7, Box8, Box9, Box10, Box11,...
0
2900
by: hitencontractor | last post by:
I am working on .NET Version 2003 making an SDI application that calls MS Excel 2003. I added a menu item called "MyApp Help" in the end of the menu bar to show Help-> About. The application calls MS Excel, so the scenario is that I am supposed to see the Excel Menu bar, FILE EDIT VIEW INSERT ... HELP. I am able to see the menu bar, but in case of Help, I see the Help of Excel and help of my application, both as a submenu of help. ...
0
9730
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...
0
10392
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10403
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
10136
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
9208
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
7671
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
5693
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3868
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3020
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.