Thread: Creating a global linked list?

  1. #1
    Registered User
    Join Date
    Nov 2007

    Creating a global linked list?

    Hi all, I have a homework assignment wherein I have to create a custom malloc and free (without ever using the standard functions for both), and I understand how to do this with a linked list, but I've run into a snag.

    I want to create a global Linked List in a .c file (which will include a .h file with the struct definitions for a linked list and nodes, and the .c file itself will be included in a driver) with just global variables and the functions for the malloc and free, but I have just learned that you cannot initialize a global variable with a function. Because of this, my plan to use sbrk() to allocate memory for the Linked List will not work. To further complicate this problem, we cannot edit the main function in the driver we are given, so I can't initialize the linked list there. So my question is: is it at all possible to create a global linked list? If so, how?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    Well, there are two steps here, right?

    One is to CREATE a global linked list - which means to have one or more global variables to represent your memory allocation(s).

    The second step is to INITIIALIZE the variable(s) with something - since you want to call sbrk(), you can't use this function as an initializer. So the solution is to use run-time initialization. The "classic" method to do this is to have a flag to say "initialized", which is set to false to begin with, and when malloc is called, you check the "initialized" flag, and call "sbrk" if you need to. [Sometimes this can be done as part of the general checking to see if sbrk() needs to be called, e.g. if you track "size available", or your linked list represents "free blocks", and it's zero (or smaller than the malloc size), then you need to call sbrk() - it then doesn't really matter if it's the first time or hundredth time that you call malloc() - you need to allocate more memory!].

    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting linked list please help with CODE
    By scarlet00014 in forum C Programming
    Replies: 3
    Last Post: 09-27-2008, 11:24 PM
  2. Need help sorting a linked list. Beginner
    By scarlet00014 in forum C Programming
    Replies: 1
    Last Post: 09-27-2008, 06:16 PM
  3. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  4. Searching a linked list for char
    By spentdome in forum C Programming
    Replies: 3
    Last Post: 05-22-2002, 11:11 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM