Thread: help with simple functions

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    2

    help with simple functions

    Does anyone see anything wrong with these simple functions?

    Basically, the "get_field" gets a word from the file of unknown length and "add_char" will add the character to the string.

    The problem lies somewhere in the "add_char" function because the memory is never realloc'd. I don't get any error messages--the word is just blank when printed. :-(

    Code:
    char *add_char(char *string,char character)
    {
        char *tmp=realloc(string,sizeof(string)+sizeof(char));
        if(tmp!=NULL)
        {
            string=tmp;
        }
        string[sizeof(string)/sizeof(char)]=character;
        return string;
    }
    
    char *get_field(FILE *inputfile)
    {
        char character;
        char *field;
        
        field=(char*)malloc(sizeof(char)*2);
        
        do
        {
            character=getc(inputfile);
            field=add_char(field,character);
        }
        while(character!='\0');
        
        field[sizeof(field)]='\0';
        
        return field;
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Read this,http://c-faq.com/malloc/reallocnull.html
    What are you trying to do?
    It looks like you are making things complicated

  3. #3
    Registered User
    Join Date
    Sep 2010
    Posts
    2
    Hahaha! I tend to do that.

    Essentially, I want to read in a word of unknown length from a file.

    It must be in C.

  4. #4
    Registered User
    Join Date
    Aug 2010
    Posts
    23
    realloc may readjust the data in the memory as it resizes the segment. so if you realloc a string chances are the returned pointer may not contain a valid string..

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Thread safety for tiny simple functions
    By CodeMonkey in forum C++ Programming
    Replies: 16
    Last Post: 12-31-2008, 12:20 AM
  2. Replies: 7
    Last Post: 11-17-2008, 01:00 PM
  3. Simple Socialising Chat Bots
    By bengreenwood in forum C++ Programming
    Replies: 10
    Last Post: 11-28-2007, 08:42 AM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. Second Program
    By cyberCLoWn in forum C++ Programming
    Replies: 28
    Last Post: 12-08-2003, 11:48 AM