Thread: malloc

  1. #1
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669

    Question malloc

    Hi!

    I have a function which input parameter is the number of words. Now I have to allocate the space for variable Words.
    Code:
    .
    .
    .
    void Function (unsigned int NoOfWords)
    {
        char *Words = 0;
    
        Words = malloc (sizeof (char) * NoOfWords);
        .
        .
        .
        free (Words);
    }
    .
    .
    .
    Is this right?
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  2. #2
    Registered User FCF's Avatar
    Join Date
    Dec 2001
    Posts
    40
    Hi, i have some questions.

    Q1: I read from a book b4, it said the malloc returns something that the C program(or compiler, not really remember) that's dun understand. So, we must cast its return value to become a valid pointer type like this:
    Code:
    char *something;
    char = (char *)malloc(sizeof(char));
    Am i right?

    Q2:
    char **words = malloc( sizeof(*words) * NoOfWords );
    the "words" is a pointer to pointer type, can it accept the malloc returned value?

    Q3: y want to use char **words to accept the returned value?


    Q4:
    words[wordnum] = malloc( strlen(a_word)+1 );
    Y want to plus 1, is it for the null character? Why dun use sizeof(a_word)?

    Q5: Can i use calloc in this situation?

    Q6: Pls refer the code below.
    Code:
    char *ch;
    ch=(char *)malloc(sizeof(char));
    The space of ch is suppose to 2 bytes(very small), but if i use the ch to accept a string with many characters, the program still run. Y?

    Sorry caz so many Y here...
    Thank you in advance for any helps.
    Life is difficult...

  3. #3
    Registered User
    Join Date
    Nov 2002
    Posts
    5
    malloc returns a void pointer to the first address of the allocated memory space. since you know that you'll be holding chars, you should cast the void pointer as a char pointer. further, since you are holding words (presumably) you should cast it as a pointer to a pointer (equivalent to a 2 dimensional array) in order to hold the collection of chars and ID them as a string.

    Salem's code is slick here:
    char **words;
    words=(char **)malloc(sizeof(*words) * NoOfWords );
    words[wordnum] = malloc( strlen(a_word)+1 );
    strcpy( words[wordnum], a_word );

  4. #4
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669
    Here's my whole code (generates the wanted number of words and write it into a file called input file and then the recursive function will reverse the order of words and write it into another file called output file). Function GenerateWords works very good but that recursive function is giving me a headache. I need that the user will not be limited with some small number of words (0-1000). It must be higher. I could define Words[10000] but this is not good. I must learn that dynamic allocation. I tried Salem's code but I get nowhere. Help me.
    Code:
    # include <stdio.h>
    # include <ctype.h>
    # include <stdlib.h>
    # include <string.h>
    # include <time.h>
    //# include <curses.h> library in linux
    
    # define BEGIN_LOWER_CASE_CHAR 97
    # define END_LOWER_CASE_CHAR    122
    
    void Reversed_Input_Order_Recursive (unsigned int NoOfWords, FILE *fin, FILE *fout);
    void WaitForKey(void);
    void GenerateWords(unsigned int NoOfWords, FILE *fin);
    
    int main ()
    {
        unsigned int NoOfWords= 0;
        char NameFin[255] = {0}, NameFout[255] = {0};
        FILE *fin= NULL, *fout= NULL;
    
    
        printf ("\nEnter number of words you want to generate: ");
        scanf ("%u", &NoOfWords);
        printf ("Enter input file name: ");
        scanf ("%s", NameFin);
        if ((fin = fopen (NameFin, "wt+")) != NULL)
        {
            GenerateWords (NoOfWords, fin);
        }
        else
        {
            printf ("\nERROR:\nI can not open file \"%s\".\nCheck if the file exists.", NameFin);
        }
        fclose (fin);
        if ((fin = fopen (NameFin, "rt+")) != NULL)
        {
            printf ("Enter output file name: ");
            scanf ("%s", NameFout);
            if ((fout = fopen (NameFout, "wt+")) != NULL)
            {
                Reversed_Input_Order_Recursive (NoOfWords, fin, fout);
            }
            else
            {
                printf ("\nERROR:\nI can not write into the file \"%s\".\nCheck if you entered the right path and file name.", NameFout);
            }
            fclose (fout);
        }
        else
        {
            printf ("\nERROR:\nI can not open file \"%s\".\nCheck if the file exists.", NameFin);
        }
        fclose (fin);
        return 0;
    }
    
    void Reversed_Input_Order_Recursive (unsigned int NoOfWords, FILE *fin, FILE *fout)
    {
        char **Words = malloc (sizeof (*Words) * NoOfWords), Word[100] = {0};
        static unsigned int i = 0;
    
    
        if (NoOfWords == 1)
        {
            fscanf (fin, "%s", Word);
            Words[i] = malloc ( strlen (Word)+1 );
            strcpy (Words[i], Word);
            fprintf (fout, "%s", Words[i]);
        }
        else if (NoOfWords > 1)
        {
            fscanf (fin, "%s", Word);
            Words[i] = malloc (strlen (Word)+1);
            strcpy (Words[i], Word);
            Reversed_Input_Order_Recursive (NoOfWords - 1, fin, fout);
            fprintf (fout, "%s", Words[i]);
        }
        i++;
    }
    void WaitForKey ()
    {
        fflush (stdin);
        getchar ();
        fflush (stdin);
    }
    void GenerateWords (unsigned int NoOfWords, FILE *fin)
    {
        char Word[10] = {0};
        time_t Seed= 0;
        unsigned int i = 0, j = 0, Character = 0, Lower = 3, Upper = 0;
    
    
        // start random generator
        srand ((unsigned) time (&Seed));
        while (i != NoOfWords)
        {
            Upper = Lower + (rand () % 4); // Upper value is between 3 and 6
            for (j = 0; j < Upper; j++)
            {
                Character = BEGIN_LOWER_CASE_CHAR + (rand () % (END_LOWER_CASE_CHAR+1 - BEGIN_LOWER_CASE_CHAR));
                Word[j] = (char) Character;
            }
            Word[j] = '\0';
            i++;
            fprintf (fin, "%s", Word);
        }
    }
    /*
    void clrscr () // erase screen in linux
    {
    	static int init;
    
        if (init == 0)
        {
            initscr();
            init = 1;
        }
        clear();
        refresh();
    }
    */
    Last edited by GaPe; 11-14-2002 at 04:56 AM.
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  5. #5
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669
    I tried this code and it works if the number of words is 100 but if the number of words is 5000 then the overflow error occurs. How to fix this error?
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  6. #6
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669
    I have to solve this problem (reverse words in a file) using recursion, iteration and iteration with stack. There must be the solution for recursion. What about if I put malloc'ed array in the recursion function? Will it work?
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  7. #7
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669
    Why can't I open new place for the stack?
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by GaPe
    I have to solve this problem (reverse words in a file) using recursion, iteration and iteration with stack. There must be the solution for recursion. What about if I put malloc'ed array in the recursion function? Will it work?
    If you have to use recursion, make a recursive read function. Make it:
    1) Read a line from a file.
    2) Word by word malloc space for it and stick in in a linked list.
    3) If you're not at the end of the file, call the read function again.

    That way, you're technicly using recursion, even though you're reading an entire line at a time instead. Otherwise, depending on the size of the file, you may run out of stack space. You cannot create "more stack space".

    Or, just use the version that will use recusion to read small files, but make your program state there is a limitation. If your teacher breaks it, tell them they were warned.

    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669
    These are my other functions and please take a look at them and tell me if anything is wrong.

    I'm not sure about the function with stack. Where should I put the free function?

    Code:
    .
    .
    .
    typedef struct
    {
        char Word[7];
        struct WORDS *Next;
    } WORDS;
    .
    .
    .
    void Reverse_Word_Order_Iterative (int NoOfWords, FILE *fin, FILE *fout)
    {
        char Word[7] = {0}, **Words= malloc (sizeof (Word) * NoOfWords);
        int i = 0;
    
        for (i = 0; i < NoOfWords; i++)
        {
            fscanf (fin, "%s", Word);
            Words[i] = malloc (strlen (Word) + 1);
            strncpy (Words[i], Word, strlen (Word) + 1);
        }
        Words[i] = '\0';
        for (i = 0; i < NoOfWords; i++)
        {
            fprintf (fout, "%s ", Words[NoOfWords-1-i]);
        }
    }
    void Reverse_Word_Order_Iterative_With_Stack (int NoOfWords, FILE *fin, FILE *fout)
    {
        WORDS *New = NULL, *Start= NULL;
        int i = 0;
    	
    	
        /* everytime opens new space for stack and adds words into a stack which are
           read from a file */
        for (i = 0; i < NoOfWords; i++)
        {
            New = malloc (sizeof (WORDS));
            fscanf (fin, "%s", New->Word);
            (WORDS *) New->Next = Start;
            Start = New;
        }
        /* read from stack and write into a file */
        do
        {
            fprintf (fout, "%s ", Start->Word);
            Start = (WORDS *) Start->Next;
        } while (Start != NULL);
    }
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  10. #10
    Registered User
    Join Date
    Nov 2002
    Posts
    1

    Cool simple ans

    void Function (unsigned int NoOfWords)

    {
    char *Words ='\0';
    Words =(char*) malloc (sizeof (char) * NoOfWords);

    .
    .
    free (Words);
    .
    }

    u can't initialize a char pointer with a 0.
    when you allocate some memory space with malloc you should do explicit typecast as shown.

  11. #11
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669
    Why can't I initialize char pointer with 0?

    Type casting malloc is not necessary (only in C++).

    Where should I put free function? Into a loop or at the end of the function?
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  12. #12
    Code Warrior
    Join Date
    Nov 2001
    Posts
    669

    Thumbs up

    Thank you Salem!
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  4. malloc and realloc
    By odysseus.lost in forum C Programming
    Replies: 3
    Last Post: 05-27-2005, 08:44 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM