Thread: problem using malloc function

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    30

    problem using malloc function

    I'm new with c and it's my first time using the malloc funtion to reserve memory and it's causing me some problems.
    I want to read a file with 3 values, all separated by a space bar.
    So this is my code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    
    int main()
    {
    char *filename;
    FILE *in;
        int i,q;
        int *reserve;
        int size;
        
        in = fopen(filename,"r");
        if(in==NULL)
        {
        perror("Datei konnte nicht geöffnet werden");
        return 0;
        }
        for(i=0;;i++) //count the entrys of the file
        {
        if(EOF==fscanf(in,"%i",&q)) break;
        }
         size = i;
    
    
        reserve =  malloc(size *sizeof(int));
         if (reserve==NULL)return 0;
        rewind(in);
    
    
        for(i=0;i<size;i++) fscanf(in,"%i",&reserve[i]);
        fclose(in);
    
    
    
    
    return 0;
    }
    However, I get the error: invalid operands of types 'int*' and 'unsigned int' to binary 'operator*' reserve = malloc(size *sizeof(int));

    I don't quite understand the malloc function so I don't know how to get rid of this error. I know the malloc function returns a pointer to the memory but I gave a wrong input.
    Can somebody pleas help me?

    Last edited by Gamma_123; 11-10-2017 at 09:41 AM. Reason: By changing size to a non pointer, I recived the error:invalid conversion from 'void*' to 'int*' [-fpermissive] reserve = malloc(size *sizeof(int));

  2. #2
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    956
    Where does "size" point to?

  3. #3
    Registered User
    Join Date
    Nov 2017
    Posts
    30
    Excuse me this was my fault. size points nowhere. I first wanted to write a function where size would have been a pointer but then I dicided to write the code in the main function.

  4. #4
    Registered User
    Join Date
    Nov 2017
    Posts
    30
    When I change size to a non pointer, I recive the error: invalid conversion from 'void*' to 'int*' [-fpermissive] reserve = malloc(size *sizeof(int));

  5. #5
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
     
     
    int main()
    {
    char *filename;
    FILE *in;
        int i, q;
        int *reserve;
        // took away pointer to it
        int size;
         // no assingnet of value (actual filename) to variabe filename. 
         // how will it actually know what file to open? 
     
        in = fopen(filename,"r");
        if(in==NULL)
        {
            perror("Datei konnte nicht geöffnet werden");
            return 0; // 0 means no error gotten. fyi
        }
        for(i=0;;i++) //count the entrys of the file
        
        {     // logic is backwards here
            // what is going to happen first,
            // EOF or reading of the file?
            
            // a while loop might be a better
            // choice to use here as well. 
            if(EOF==fscanf(in,"%i",&q)) break;
             
        }
        size = i;
     
        // reserve = (int *)malloc(sizeof(int));
         // 'size' is the size you want, not int in this case.
         // because size has a size value within itself.  
        
        // reserve = (int *)malloc(sizeof(size));
        // gets amount of value inside of size. 
         reserve = (int *)malloc(sizeof(int) * size);
    
        // reserve =  malloc(size * sizeof(int));
         if (reserve==NULL)return 0;
        rewind(in);
     
     
        for(i=0;i<size;i++) fscanf(in,"%i",&reserve[i]); 
        fclose(in);
     
     
     
     
    return 0;
    }
    Link tells a good bit of what you need to know about your malloc'ing

    comments are for some more issues you are going to have
    after you figure out your malloc. You might need to check fscanf return value as well.


    C - Malloc - Learn C Programming
    Last edited by userxbw; 11-10-2017 at 09:59 AM.

  6. #6
    Registered User
    Join Date
    Nov 2017
    Posts
    30
    I can compile the programm now. Thank you! The filname should later be written in the terminal. I just don't quite understand the malloc function! What does this function expect as an input??

  7. #7
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Quote Originally Posted by Gamma_123 View Post
    I can compile the programm now. Thank you! The filname should later be written in the terminal. I just don't quite understand the malloc function! What does this function expect as an input??
    again

    C - Malloc - Learn C Programming

  8. #8
    Registered User
    Join Date
    Jun 2017
    Posts
    157
    Why do you want to use malloc at all if you know beforehand how many numbers you want to read?
    Better to follow to KISS priciple
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    #define MAX_NUMBERS 3
    
    int main()
    {
      char filename[] = "somename.txt";
      FILE *in;
      int data[MAX_NUMBERS] = {0}; 
      int num_read = 0;
      int i = 0;
    
      in = fopen(filename, "r");
      if (in == NULL)
      {
        perror("Datei konnte nicht geöffnet werden");
        return errno;
      }
      while (num_read < MAX_NUMBERS && fscanf(in, "%d", &data[num_read]))
        num_read++;
    
      printf ("%d numbers read\n\n", num_read);
      for (; i < num_read; i++)
        printf("Number %d: %d\n", i, data[i]);
    
      fclose(in);
      return 0;
    }

  9. #9
    Banned
    Join Date
    Aug 2017
    Posts
    861
    for the unknown you can read ahead to get bytes of data, figure out how to find the spaces using fgets output to 'c' then do the math to figure out what amount of data is minus spaces.

    you can use 'c' to get words, spaces, lines count then work with which ever to get what you want done done.
    Code:
        int size = 0, count = 1;
        char c = '\0';
        // seek to eof
        while ( (c = fgetc(in)) != EOF) {
               size = ftell(in);
               
               if ( c == ' ' )
                    count++;
           printf("count = %d : size = %d = %c\n",count, size, c);
    }
    printf("words read = %d\n", count);
    file contains
    Code:
    $ ./mallocing
    count = 1 : size = 1 = 2
    count = 1 : size = 2 = 3
    count = 1 : size = 3 = 4
    count = 2 : size = 4 =  
    count = 2 : size = 5 = 2
    count = 2 : size = 6 = 3
    count = 2 : size = 7 = 
    
    words read = 2
    str = 234 23
    Last edited by userxbw; 11-10-2017 at 11:58 AM.

  10. #10
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    956
    Quote Originally Posted by Gamma_123 View Post
    When I change size to a non pointer, I recive the error: invalid conversion from 'void*' to 'int*' [-fpermissive] reserve = malloc(size *sizeof(int));
    It builds and runs fine for me. Are you trying to compile the program as C++? C++ is more strict about converting void* to other types.

    Edit to add: in general, you shouldn't cast the return value from malloc. See FAQ > Casting malloc.
    Last edited by christop; 11-10-2017 at 01:34 PM.

  11. #11
    Registered User
    Join Date
    Nov 2017
    Posts
    30
    Than maybe I use a different compiler. I use a mingw compiler but I don't know which version. Is there a way to check this with cmd? Is there also a different when I compile c codes than c++ codes? I compile(windows10) like:g++ -o programm programm.c?
    The main reason why I wan't to use the malloc function is becaus it's asked for in my homework but thanks for all the advice!

  12. #12
    Guest
    Guest
    Is there a way to check this with cmd?
    Invoking gcc --version from the command line should work.

    I compile(windows10) like:g++ -o programm programm.c?
    g++ is for when you want to compile as C++. You need to type gcc instead.
    Last edited by Guest; 11-11-2017 at 07:12 AM.

  13. #13
    Registered User
    Join Date
    Nov 2017
    Posts
    30
    Thank yo very much. I have version 5.3.0. I now want to read a file with cmd like: program file.dat and get the perror message and "Invalid argument". Does somebody now why this is happening?

  14. #14
    Guest
    Guest
    Maybe you forgot to add arguments to main, like so?

    Code:
    int main(int argc, char* argv[])
    {
        // process argv here
        return 0;
    }
    You can find examples on parameter passing online.

  15. #15
    Banned
    Join Date
    Aug 2017
    Posts
    861
    does main look like this,
    Code:
    int main(void)
    or this
    Code:
    int main ( int argc, const char **argv)
    ?

    whence you get that figured out, then you need to learn zero based counting and how argc works with argv.

    0 = program name, then count up from there left to right on the command-line interface ( cli ) for whatever is written on it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help me with malloc function
    By priyaxen in forum C Programming
    Replies: 2
    Last Post: 10-07-2013, 12:25 AM
  2. Replies: 1
    Last Post: 12-07-2012, 10:00 AM
  3. Can't malloc from within a function
    By synthetix in forum C Programming
    Replies: 5
    Last Post: 11-02-2011, 12:28 PM
  4. Malloc function problem
    By bouvett in forum C Programming
    Replies: 5
    Last Post: 09-13-2011, 03:05 AM
  5. using malloc in a function
    By cuizy in forum C Programming
    Replies: 10
    Last Post: 08-13-2009, 01:56 PM

Tags for this Thread