Hi there, I'm very new to C program, I'm about to write a function that read input from standard input, and then returns a pointer to the next word, then i can use it later to print out all the words, but when i run it, i got "Segmentation fault " at the end of output line, this is my code, I've been working on this for a few days, but I still cannot get right, can someone can help me? please! - #include <stdio.h>
-
#include <stdlib.h>
-
#include <string.h>
-
#include <ctype.h>
-
/* assume fp just stdin, and rCase is True if the case of the returned word
-
* is to be exactly same as in the input
-
**/
-
char* readWord (FILE* fp, int rCase)
-
{
-
char buffer[100];
-
char* nextWord = NULL;
-
int ch, i = 0;
-
int wordLength = 0;
-
-
while ((ch = fgetc(fp)) != EOF && !(isalpha(ch)))
-
;
-
-
while (isalpha(ch)) {
-
if (!retainCase)
-
buffer[wordLength++] = tolower(ch);
-
else
-
buffer[wordLength++] = ch;
-
-
nextWord = buffer;
-
buffer[wordLength] = '\0';
-
ch = fgetc(fp);
-
}
-
return nextWord;
-
}
-
-
int main(int argc, char *argv[])
-
{
-
char* new;
-
while (argc == 1) {
-
new = readWord(stdin,0);
-
printf("%s\n", new);
-
}
-
return (EXIT_SUCCESS);
-
}
9 2603
Note that your 'buffer' array is a local array variable and its allocated on the stack.
When the function returns the stack frame is lost for the posterity and your
buffer array variable is too. Before you want to return that word you should
malloc() enough bytes, copy the word over to that allocated memory and return
whatever malloc() returned.
The caller of your function is responsible then for free()-ing that memory afterwards
(if needed).
kind regards,
Jos
Note that your 'buffer' array is a local array variable and its allocated on the stack.
When the function returns the stack frame is lost for the posterity and your
buffer array variable is too. Before you want to return that word you should
malloc() enough bytes, copy the word over to that allocated memory and return
whatever malloc() returned.
The caller of your function is responsible then for free()-ing that memory afterwards
(if needed).
kind regards,
Jos
Jos, what are you saying? "if needed"? One should always cleanup memory that was allocated. I've heard the arguments that the operating system will clean up all allocated memory upon exit, but that is a bunch of crap. It makes for lazy programmers who then forget to implement best practices when it is required.
I'm disappointed Jos, Tisk tisk. ;)
Other than my tirade to Jos, what was said is correct. Further to what Jos said, if you don't want to use malloc(), you can instead allocate the memory in the caller on the stack like you have done in the readWord(), and pass that array and its size to the readWord(). The return value could be then reserved for returning the function's status.
BTW, if this is an assignment, I assume that you were given permission not to check to see if you have exceeded the char array boundary by making the array fairly large?
Further, I don't see how you could have ran the code as this shouldn't compile. retainCase is not defined.
Just adding my 2 cents. ;)
Adrian
Jos, what are you saying? "if needed"? One should always cleanup memory that was allocated. I've heard the arguments that the operating system will clean up all allocated memory upon exit, but that is a bunch of crap. It makes for lazy programmers who then forget to implement best practices when it is required.
I'm disappointed Jos, Tisk tisk. ;)
From IBM/VM (CMS and TSO) through Harris/VOS, VAX/VMS, quite a bunch
of different Un*xes (some of them even smelled funny), Linux and even MS
Windows, all of them were just clever enough to reap the memory allocated
to the process after it had finished no matter in what horrible way.
Only CPM and MS/DOS (the unprotected memory thingies) were too stupid.
Of course the same counts for a lot of embedded systems too except for
Symbian, that's an extremely clever little embedded OS and an exception
to the embedded rule.
That's why I added the "if needed" phrase ;-)
kind regards,
Jos
From IBM/VM (CMS and TSO) through Harris/VOS, VAX/VMS, quite a bunch
of different Un*xes (some of them even smelled funny), Linux and even MS
Windows, all of them were just clever enough to reap the memory allocated
to the process after it had finished no matter in what horrible way.
Only CPM and MS/DOS (the unprotected memory thingies) were too stupid.
Of course the same counts for a lot of embedded systems too except for
Symbian, that's an extremely clever little embedded OS and an exception
to the embedded rule.
That's why I added the "if needed" phrase ;-)
kind regards,
Jos
Yes, but by saying "if needed", you are cultivating bad habbits in programmers.
Sometimes, a function is reused and then the memory leak becomes a persistant problem while the code is running.
They should always think it is needed as this will reduce errors later on in their coding careers.
Adrian
Yes, but by saying "if needed", you are cultivating bad habbits in programmers.
Sometimes, a function is reused and then the memory leak becomes a persistant problem while the code is running.
They should always think it is needed as this will reduce errors later on in their coding careers.
Adrian
True; I just put the ball on their side so they should take their responsibilities.
I am in the role of the lazy advisor (*) you know and I don't want to spoonfeed ;-)
kind regards,
Jos
(*) "memory leaks are good; otherwise you get bit rust"
True; I just put the ball on their side so they should take their responsibilities.
I am in the role of the lazy advisor (*) you know and I don't want to spoonfeed ;-)
kind regards,
Jos
(*) "memory leaks are good; otherwise you get bit rust"
I think you just want to keep your position safe from being overrun by new coders. :p ;) Job security I think its called. :D
Me, I want to build a tower of Bable, without it falling back to the Earth agian. ;)
Adrian
I think you just want to keep your position safe from being overrun by new coders. :p ;) Job security I think its called. :D
Me, I want to build a tower of Bable, without it falling back to the Earth agian. ;)
Adrian
Duh, I'm the CEO/CTO/CFO/Coffee Lady/Programmer/Janitor of my own
company so "I am the law!" ;-)
kind regards,
Judg^H^H^Hos
Duh, I'm the CEO/CTO/CFO/Coffee Lady/Programmer/Janitor of my own
company so "I am the law!" ;-)
kind regards,
Judg^H^H^Hos
Ahh, so you are related to Bill G. eh? Your attidute is so much clearer now, junk is all you know. :D :p
Adrian
Back to work children :rolleyes:
Actually I quite enjoyed this one :D If you feel like taking your discussion on Memory Allocation to the Software Development forum please feel free. I'm sure you'll have many participants to the discussion on both sides.
Mary
Sign in to post your reply or Sign up for a free account.
Similar topics
by: John Bailo |
last post by:
The c# *return* statement has been bothering me the past few months.
I don't like the fact that you can have different code paths in a method
and have multiple return statements. To me, it...
|
by: John N. |
last post by:
Hi All,
Here I have a linked list each containing a char and is double linked.
Then I have a pointer to an item in that list which is the current
insertion point.
In this funtion, the user...
|
by: tuko |
last post by:
Hello kind people.
Can someone explain please the following code?
/* Create Storage Space For The Texture */
AUX_RGBImageRec *TextureImage; /* Line 1*/
/* Set The Pointer To NULL...
|
by: vb |
last post by:
Hi all,
I am a newbie in C and i want to know what all pointer conversions are
"legal" according to ANSI C standard. For Example, int* to char*,
some_struct* to char* and so on ..
According to...
|
by: Erik de Castro Lopo |
last post by:
Hi all,
The GNU C compiler allows a void pointer to be incremented and
the behaviour is equivalent to incrementing a char pointer.
Is this legal C99 or is this a GNU C extention?
Thanks in...
|
by: vim |
last post by:
hi guys
this is my code
#include<stdio.h>
main()
{
char *p={"hello" ,"world" ,"Nice","show"};
char **p1;
}
I want to print the string "helwornicsho" by using ptr increment or
|
by: David Deharbe |
last post by:
Hi,
Assuming that a pointer to void is always a multiple of 4 provides an
opportunity to use as tags the two bits that are always 0. Knowing that
several experts on the ISO99 C standard should...
|
by: Jim Langston |
last post by:
I remember there was a thread a while back that was talking about using the
return value of a function as a reference where I had thought the reference
would become invalidated because it was a...
|
by: Davy |
last post by:
Hi all,
I am writing a function, which return the pointer of the int. But it
seems to be wrong. Any suggestion?
int * get_p_t(int t) {
return &t;
}
int main()
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
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,...
|
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...
|
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...
| |