Thread: Newbie question about string processing

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    7

    Newbie question about string processing

    Hi, the question I am about to ask is a part of bigger home work task. However I am stuck at this and do not know how to proceed further. My task is to receive input from the user, the input is arbitrary number of strings ending, with '\0' character. Once I am done with inputing strings I should save them (this part I think I am done with). The next part is to split up saved input in to separate strings, the splitting should be done whenever I encounter new line character '\n'.
    Right now all I want is to out put fragmented strings. Unfortunately code works in a way that I can not understand. Lets say input is following:
    Code:
    First line of text 1
    Second line of text 2
    Third line of text 3
    Running program with the input above, outputs following:
    Code:
    Firs
    Second Q te of text 2
    Third line of text 3
    �
    Segmentation fault
    Code of the program is
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    char *ReadInput(void);
    void Divide (char text[]);
    
    int main(void) {
        char *textReceived;
    
        textReceived=ReadInput();
        Divide(textReceived);
    
        return 0;
    }
    void Divide (char text[]) {
        char *tmpString=NULL;
        int i=0, j=0;
        tmpString=(char *)malloc(sizeof(char));
    
        while ((text[i])!='\0') {
            if ((tmpString[j])=='\n') {
                printf("%s\n", tmpString);
                tmpString=NULL;
                j=0;
                i++;
            }
            else
                tmpString[j++]=text[i++];
        }
    }
    char *ReadInput(void) {  
        char *string;
        int i=0;     
        string=(char *)malloc(sizeof(char));
        while ((string[i++]=getchar())!=EOF)
            ;
        return string;
    }
    I do not understand what is wrong with the code, please help.
    Regards,
    Alex

  2. #2
    Cogito Ergo Sum
    Join Date
    Mar 2007
    Location
    Sydney, Australia
    Posts
    463
    Check out the strings library
    =========================================
    Everytime you segfault, you murder some part of the world

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    For starters this line is only allocating enough memory to hold a single character of data:
    Code:
    string=(char *)malloc(sizeof(char));

  4. #4
    Ex scientia vera
    Join Date
    Sep 2007
    Posts
    477
    You should get a decent IDE, such as Visual Studio, as it would with 100% certainty catch that error, not necessarily at compile time, but at runtime and then give you a nice description going something like: "Heap corruption occurred" and break at the line of code that caused it.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    It will break when you're freeing the corrupted memory.
    But it also usually states the address of where the memory was allocated so you can hunt down the bug with breakpoints.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Registered User
    Join Date
    Apr 2008
    Posts
    7
    For starters this line is only allocating enough memory to hold a single character of data:
    Code:

    string=(char *)malloc(sizeof(char));
    The thing is that input size is arbitrary, I do not know it before hand. Should I be reallocating memory before each new item added to string ?

    Such as:
    Code:
    string=(char *)malloc(sizeof(char));
    while ((string[i++]=getchar())!=EOF)
            string=(char *)realloc(string, sizeof(string)+sizeof(char));

  7. #7
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    I would suggest using a buffering approach. Since several input functions (including getchar() ) are already line buffered, you could save yourself the Devide() step. I mean, since you're going to use the input after it's been broken into lines anyway, why not simply read line-by-line, rather than trying to read all the input in one big blob?

    You could read a big line like this:

    1. Create initial storage with malloc(), say 256 characters.
    2. Have a variable remember this number.
    3. Read characters until you've filled up the buffer or found an '\n'
    4. If necessary, reallocate (e.g.):
    Code:
    void * temp = NULL;
    line_length *= 2; 
    temp = realloc( line, line_length );
    if ( temp == NULL )
      /**handle allocation failure**/
    line = temp;
    5. Repeat 3 and 4 as necessary.
    6. Termainate your string.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. newbie with string question
    By tmitch in forum C Programming
    Replies: 2
    Last Post: 11-13-2005, 06:58 PM
  3. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 12:47 PM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. String array question
    By gogo in forum C++ Programming
    Replies: 6
    Last Post: 12-08-2001, 06:44 PM