Thread: A custom gets function

  1. #16
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Well, data-memory in a C program falls into three categories:
    - Global variables.
    - Stack.
    - Heap.

    These are distinct areas of memory, so they are different addresses. Global variables are given their memory address by the compiler when the program is compiled. As the name indicates, this are all variables declared outside of functions, and also static variables inside functions.

    The stack is assigned by the OS when the application is started. The stack holds all variables inside functions, arguments to functions and the return address so that the code can get back to the previous function when this one returns. Whenever you call a function, the stack is counted down (in all systems I'm aware of the stack grows towards zero), and any local variables are formed by the space between the curren stack pointer and the return address back to the previous function. When the function returns, the stack is counted back up again, and the return address is fetched and the code jumps back to where it came from. This means that any variables that "lived" on the stack are "gone" whwn you return to the calling code. The size of the stack is usually fixed by the OS when the application is started. The stack is being constantly re-used by different functions, and the more call levels you have (for example recursive functions), the more stack is being used.

    The heap is a place where applications can request "free memory", typically using malloc() or the C++ operator new. It is not "destroyed" when the function returns, instead you have to free the memory by calling free() or use the C++ operator delete. The heap is generally not of a fixed size, as long as there is more space available in the system, it will keep growing, so if you have a machine with lots of memory (say 2GB RAM), you can easily allocate some 1.5-1.8GB of memory in your application. The heap is used to store things that are of "unknown quantity/size".

    The problem with "freeing" memory that doesn't belong to the heap is caused by the fact that the heap management functions (malloc for example) have their private data structure to track what is used and what is free on the heap, and that data structure will not work for memory from for example the stack - and even if it does work, what happens when you ask malloc for some memory, it decides to give the stack area back to the function, and they you call some function that also uses that area of the stack - that would cause the same area of memory to be used for different stuff at the same time - which like most things doesn't work!

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  2. #17
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by aijazbaig1 View Post
    So you mean I should instead pass to this function a pointer to b2(the string b2 that is). And my mygets function should then allocate more space as and when needed?
    Well, yes. If it accepts a pointer to a pointer in main, it can dynamically adjust the buffer.

    .. you also said ..well...as before if I do that allocation within the function won't it get allocated on the stack again?...is there a way to specify that I'd like to have it allocated on the heap?...
    Yes, you use malloc (or calloc) and a pointer.

    What exactly do you mean by a buffer..I hope its just a memory block pointed to by some pointer right?...
    Yes. A buffer or an array. A contiguous memory block.
    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.

  3. #18
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    In case anyone's interested: I created a function of this sort for codeform.
    Code:
    /*! A dynamic-memory allocating clone of fgets(). Reads characters from fp,
        storing them in \a line starting with (*line)[len].
        \param line The resizeable string to store characters in.
        \param len The position in \a line to start storing characters at.
        \param alen The amount of memory currently allocated (multiple of BUFSIZ).
        \param fp The file to read the characters from.
        \return The new length of the string (\a len modified). It will be the same
        as \a len if no characters were read before EOF was encountered.
    */
    size_t get_string(char **line, size_t len, size_t *alen, FILE *fp) {
        char *p;
        int c = 0;
    
        do {
            if(c == '\n') c = 0;
            else c = getc(fp);
    
            if(c == EOF) {
                c = 0;
            }
    
            if(len >= *alen) {
                if(*alen) *alen *= 2;
                else *alen = BUFSIZ;
    
                p = realloc(*line, *alen);
    
                if(!p) out_of_memory(__FILE__, __LINE__);
    
                *line = p;
            }
    
            (*line)[len++] = c;
        } while(c);
    
        return len - 1;
    }
    Note that this code is rather old -- if I wrote it now, I'd almost certainly do things differently.

    The above code doubles the allocated length when it runs out of space -- very good when reading a lot of data. It seems such a simple idea once you've seen it, but it's hard to think up by yourself.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. Troubleshooting Input Function
    By SiliconHobo in forum C Programming
    Replies: 14
    Last Post: 12-05-2007, 07:18 AM
  3. Brand new to C need favor
    By dontknowc in forum C Programming
    Replies: 5
    Last Post: 09-21-2007, 10:08 AM
  4. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  5. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM