Thread: realloc

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    117

    realloc

    I have an assignment to read a file with the list of months in order and store them which is done at the beginning of the program. 2nd I need to take another file with a list of dates such as
    January 17,2004. (one on each line). I need to take that file and add a count/update a count for the that year and month. So that'd be January 2004 that would be updated.

    Anyways I initialize the memory of the structure for each month name while reading the first file using malloc. Now I need to add memory to this every time I see this month. I plan on storing the year for each month that comes up into it's own structure and then sorting the years later. I need to add memory as I said so I'm trying to use realloc and when I use this in the for loop

    Code:
            *month_name = realloc( month_name, (counter2+1)* sizeof(*month_name));

    It says assignment makes integer from pointer without a cast (line 84)

    when I use
    Code:
           month_name = realloc( month_name, (counter2+1)* sizeof(*month_name));
    It says incompatible types in assignment.

    What exactly am I doing wrong on my realloc for memory?


    full code is below
    Code:
    #include <stdio.h>#include <stdlib.h>
    #include <string.h>
    
    
    
    
    struct struct_of_months
    {
           char months[20];
    };
    
    
    struct struct_of_years
    {
       char year[4];
    };       
    
    
    int main(void)
    {
        FILE *fp;
        int counter1 = 0;
        int counter2 = 0;
        int line_len;
        int i=0;
        int test;
        char buffer[50];
        char month_name[50];
        char **month_and_year = NULL;
        char *month;
        char *day;
        char *year;
        char *p;
        struct struct_of_months *array_of_months = malloc (sizeof(*array_of_months));
    
    //Opens the first file and stores the months individually in list_of_months 
        if ( (fp = fopen("months.txt", "r" )) == NULL )
        {
        printf("Couldn't open file\n");
        exit(1); 
        }
        while(fgets(buffer, sizeof(buffer), fp))
        {   
    //stores months in an array of structures              
            if (counter1>0)
            array_of_months=realloc(array_of_months,(counter1+1)*sizeof(*array_of_months)); 
            strcpy(array_of_months[counter1].months, buffer);
    
    //initializes memory for the years in each month
            sprintf(month_name,"%s", month);
            struct struct_of_years *month_name = malloc (sizeof(*month_name));
            counter1++;         
        }   
    fclose( fp );
    
    //Opens the second file and stores the month in month and year in year.                
        if ( (fp = fopen("dates.csv", "r" )) == NULL )
        {
        printf("Couldn't open file\n");
        exit(1); 
        }
    
        while(fgets(buffer, sizeof(buffer), fp))
        {                                                        
         month_and_year = realloc(month_and_year, (counter2+1) * sizeof(*month_and_year) );
         line_len = strlen(buffer);
         month_and_year[counter2] = calloc(line_len+1, sizeof(buffer));
         
         if ((p = strchr(buffer, '\n')) != NULL)
          *p = '\0';
    
    //stores month, days, and years 
         strcpy(month_and_year[counter2],buffer);
         month = strtok (month_and_year[counter2], " ");
         day = strtok (NULL, ",");
         year = strtok (NULL, ",");
         
    //for loops testing each month to the month on that line   
         for(i = 0; i < counter1; i++)
         {
          test = strncmp(month, array_of_months[i].months, 3);
          sprintf(month_name,"%s", month);
          if(test ==0)       
            month_name = realloc( month_name, (counter2+1)* sizeof(*month_name));       
         }
            counter2++;         
        } 
    
    //frees the memory for the years      
      for(i = 0; i < counter1; i++)
     {
       sprintf(month_name,"month-%d", counter1); 
       free(month_name);
     }  
    fclose( fp );                                
    free(month_and_year); 
    
    
     getchar();
     return 0;
    
    }



    Last edited by mgracecar; 03-16-2012 at 01:57 PM.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You have two variables with the same name. Look at line 28 and line 51. The declaration on line 51 is only valid inside the set of curly braces you declare it in, not outside of it. That means it's only valid on lines 43-53 (and the char array version can't be "seen" inside that block). Thus, when you realloc on line 84, you're trying to realloc the char array declared on line 28. An explination of the two error messages:
    Code:
    *month_name = realloc(...)
    This gives you "assignment makes integer from pointer..." because month_name (the name of the array) acts as a pointer to the first element (pointer to a char), so *month_name is the char itself (a char is just a tiny int). realloc returns a void *. A void * can be assigned to any other pointer type, no problem, but it can't be assigned to a char or int. Thus, the compiler is telling you, if you wish to do this crazy assignment, you need to type cast it, because I won't do it on my own.
    Code:
    month_name = realloc(...)
    This gives you "incompatible types in assignment" because you can't assign to arrays like that. The name of the array acts as a pointer to the first element, but you can't change where it points. Assigning realloc to month_name is trying to change where month_name points. Read this: Question 6.5.

    EDIT: One more thing. You always need to use a temp pointer when using realloc. If you assign the return of realloc to the original variable, and realloc fails, you lose the pointer to the original memory. That means you can't access the old data there, and you can't free it, which is a memory leak. Something like this:
    Code:
    temp_pointer = realloc(old_pointer, new_size)
    if (temp_pointer == NULL)
        error
    else
        old_pointer = temp_pointer
    Last edited by anduril462; 03-16-2012 at 02:20 PM.

  3. #3
    Registered User
    Join Date
    Feb 2012
    Posts
    117
    Ok, the point of my array of month_name was to change the name of month_name From "January" all the way to "December". Instead of hard coding it all. Then I was wanting to make memory for structures of those names. That way I could have a structure for each month and have the years stored inside of it.

    But as you said, I'm apparently going about this wrong. Hmm, so is my method of thinking even correct to a semi-easy solution on this one? Or should I try to organize these years with the months in another way? I see what you mean on the struct month_name is not seen everywhere. I'd have to either find a way to allocate it elsewhere or just make a different approach it seems?

  4. #4
    Registered User
    Join Date
    Feb 2012
    Posts
    117
    If I change that top part to this, that would do kind of what I'm intending right? The array of month_name would have the month names and use those to allocate memory to initialize the structures for each month?
    Not sure how to test this exactly since It's a structure with nothing in it yet.


    Code:
    int main(void){
        FILE *fp;
        char buffer[50];
        char month_name[50];
        char **month_and_year = NULL;
        int counter1 = 0;
        int counter2 = 0;
        int line_len;
        char *month;
        char *day;
        char *year;
        int i=0;
        int test;
        char *p;
        struct struct_of_months *array_of_months = malloc (sizeof(*array_of_months));
    
    
    //Opens the first file and stores the months individually in list_of_months 
        if ( (fp = fopen("months.txt", "r" )) == NULL )
        {
        printf("Couldn't open file\n");
        exit(1); 
        }
        while(fgets(buffer, sizeof(buffer), fp))
        {
            if (counter1>0)
            array_of_months=realloc(array_of_months,(counter1+1)*sizeof(*array_of_months)); 
            strcpy(array_of_months[counter1].months, buffer);      
            counter1++;         
        }   
    fclose( fp );
            
            for (i = 0; i< counter1; i++)
            {
            sprintf(month_name,"%s", array_of_months[i].months);
            struct struct_of_years *month_name = malloc (sizeof(*month_name));
            }

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,664
    Continued here -> Reallocating problem.
    Try to keep 1 thread per topic.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. realloc
    By salvadoravi in forum C Programming
    Replies: 1
    Last Post: 01-15-2008, 08:15 PM
  2. realloc
    By gustavosserra in forum C Programming
    Replies: 3
    Last Post: 08-05-2004, 07:35 PM
  3. Realloc help
    By Padawan in forum C Programming
    Replies: 2
    Last Post: 04-01-2004, 10:32 PM
  4. Realloc
    By vasanth in forum Tech Board
    Replies: 6
    Last Post: 03-13-2004, 12:14 PM
  5. realloc() ????????
    By RoshanX in forum C Programming
    Replies: 3
    Last Post: 10-12-2003, 07:03 PM