473,387 Members | 1,876 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

return pointer to next word

5
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!

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5. /* assume fp just stdin, and rCase is True if the case of the returned word
  6.  * is to be exactly same as in the input
  7.  **/ 
  8. char* readWord (FILE* fp, int rCase)
  9. {
  10.     char buffer[100];
  11.     char* nextWord = NULL;
  12.     int ch, i = 0;
  13.     int wordLength = 0;
  14.  
  15.     while ((ch = fgetc(fp)) != EOF && !(isalpha(ch)))
  16.         ;
  17.  
  18.     while (isalpha(ch)) {
  19.         if (!retainCase) 
  20.             buffer[wordLength++] = tolower(ch);
  21.         else 
  22.             buffer[wordLength++] = ch;
  23.  
  24.         nextWord = buffer;
  25.         buffer[wordLength] = '\0';
  26.         ch = fgetc(fp);
  27.     }
  28.     return nextWord;
  29. }
  30.  
  31. int main(int argc, char *argv[])
  32. {
  33.     char* new;
  34.     while (argc == 1) {
  35.         new = readWord(stdin,0);
  36.         printf("%s\n", new);
  37.     }
  38.     return (EXIT_SUCCESS);
May 1 '07 #1
9 2603
JosAH
11,448 Expert 8TB
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
May 1 '07 #2
AdrianH
1,251 Expert 1GB
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
May 1 '07 #3
JosAH
11,448 Expert 8TB
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
May 1 '07 #4
AdrianH
1,251 Expert 1GB
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
May 1 '07 #5
JosAH
11,448 Expert 8TB
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"
May 1 '07 #6
AdrianH
1,251 Expert 1GB
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
May 1 '07 #7
JosAH
11,448 Expert 8TB
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
May 1 '07 #8
AdrianH
1,251 Expert 1GB
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
May 1 '07 #9
MMcCarthy
14,534 Expert Mod 8TB
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
May 2 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

94
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...
5
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...
35
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...
10
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...
27
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...
14
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
10
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...
68
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...
49
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()
0
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,...
0
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$) { } ...
0
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...
0
BarryA
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
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...
0
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,...
0
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...
0
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...

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.