Thread: Error from random matrix programme

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    3

    Error from random matrix programme

    Evening all,

    I've written a working code to create a matrix (the size of which is defined by the user) and fill it with random values and print out the result.

    Why then am I posting it here? Well whenever I run it, as I press the key to close the programme I get an error message saying my programme has stopped working. Can any one help me with this?
    Theres two places I think its occuring but I'm not entirely sure. One place it could be is in my use of pointers (farily new to them) and maybe also in the malloc/free functions

    Any help is help
    Cheers


    Code:
    // A programme to create a user defined matrix and fill it with random values
    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>
    #include <malloc.h>
    #include <time.h>
    //FUNCTIONS
    //Function to return a random double in the range [0.0,100.0]
    double random()
    {
           double n,m;
           n=rand();
           m=100*n/RAND_MAX;
           return(m);
           }
    //Function to populate matrix with random values:
    double *rand_matrix(double *mat, int rows, int cols)
    {
           for (int i=0 ; i<rows ; i++)
           {   for (int j=0 ; j<cols ; j++)
               {   *(mat+i*rows+j)=random();
               }
            }
           return(mat);
    }           
    //Function to print out a matrix:
    void print_matrix(double *mat,int rows,int cols)
    {
         for (int i=0 ; i<rows ; i++)
         {   for (int j=0 ; j<cols ; j++)
             {   printf("%5.2lf    ",*(mat+i*rows+j));
             }
             printf("\n");
         }
    } 
                        
     
     
     
     
     
    
    int main ()
    {
    //Before programme starts I must seed the random generator.
    srand(time(0));
        
        
    //initialise variables;
    int m,n,err,yesno=0;
    double **ptr_rows=0,**user_ptr=0,*elem_ptr=0;
        
    //Take input from the user for the size of the matrix
    do
    {
        printf("Enter the number of Rows and Collumns in the form m n\n>> ");
        err=scanf("%d %d",&m,&n);
        _flushall();
                      if ((err!=2)||(m<=0)||(n<=0))
                         {do
                           { 
                           printf("\nERROR you must have an integer number of rows and collumns\nEnter the number of Rows and Collumns in the form m n\n>> ");
                           err=scanf("%d %d",&m,&n);
                           _flushall();
                                         if ((err==2)&&(m>0)&&(n>0))
                                         break;
                           }while ((err!=2)||(m<=0)||(n<=0));
                           }
        printf("\nThe size of the matrix you have decided to use is %dx%d\npress 'N' to enter a different size or press any key to continue.\n",m,n);
        scanf("%c",&yesno);
        _flushall();
    }while ((yesno=='N')||(yesno=='n'));
    
    //Allocate memory for this matrix
    ptr_rows =(double**)  malloc(m*sizeof(double*));
    user_ptr=ptr_rows;
    for( int i=0 ; i<m ; i++)
    {    *user_ptr=(double*)malloc(n*sizeof(double));
         elem_ptr=*user_ptr;
         for(int j=0 ; j<n ;j++)
         *elem_ptr++=1.0;
         user_ptr++;
    }
    user_ptr=ptr_rows;
    //Use rand_matrix function to create a ransom Matrix
      
    print_matrix((double*) rand_matrix(*user_ptr,m,n),m,n);    
        
        
        
        
        getch();
    //free the memory from the matrix
    for( int i=0; i<n ; i++);
    free(*user_ptr++);
    free(ptr_rows);
        return (0);
    }

  2. #2
    Registered User
    Join Date
    Nov 2011
    Posts
    29
    There's an issue in free().
    You're pointers are like this. ptr_rows <-- user_ptr <-- elem_ptr
    So esentially the latter 2 are all pointing to the memory of ptr_rows.
    This means you only need to do free(ptr_rows)

    In your code if you free user_ptr, then it will result in an error when freeing ptr_rows, because that memory is already freed. You can also see that from the run error, in mine it said "double free or corruption"

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    A few things to note:
    • You made some effort to indent your code, which is good, but it still could be improved, especially for the main function.
    • The first parameter of rand_matrix is a double*. It looks like it should be a double** instead.
    • Instead of writing *(mat+i*rows+j), write mat[i][j]. This notation is far less mistake prone.
    • Instead of messing around with user_ptr and elem_ptr, just access ptr_rows[i] and ptr_rows[i][j].
    • Observe that there is an extra semi-colon at the end of your last for loop.


    Quote Originally Posted by naturegirl
    This means you only need to do free(ptr_rows)
    No. free should also be used for each inner dynamic array. This is a consequence of allocating each inner dynamic array in a loop.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Nov 2011
    Posts
    29
    Quote Originally Posted by laserlight View Post

    No. free should also be used for each inner dynamic array. This is a consequence of allocating each inner dynamic array in a loop.
    Oh I see! Thanks Hm weird, what did the error about the double free mean then?
    I thought it meant the first free, because when I removed it, the program worked fine.

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    3
    Thanks for the replies, I would have gotten back sooner but my internet was down. Yes I've gotten rid of all the user_pointer stuff as it was pointless, in fact I rewrote the whole code taking into account what you said. Fixing the errors and now when i run it, I don't get any errors.

    Thanks for the help

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Matrix - Logic error?
    By FernandoBasso in forum C Programming
    Replies: 2
    Last Post: 11-23-2011, 11:50 AM
  2. strange matrix error
    By engg in forum C Programming
    Replies: 7
    Last Post: 10-16-2011, 08:01 PM
  3. Matrix Multiplication 2 - Error Message
    By dlf in forum C++ Programming
    Replies: 5
    Last Post: 12-06-2005, 04:50 PM
  4. Error allocating matrix
    By gustavosserra in forum C Programming
    Replies: 5
    Last Post: 09-25-2003, 02:07 PM
  5. error handler and 2D / Matrix array
    By Yoshi in forum C++ Programming
    Replies: 2
    Last Post: 12-06-2002, 09:40 PM