GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 17-Jan-2007, 02:54
Cristovao Cristovao is offline
New Member
 
Join Date: Jan 2007
Posts: 6
Cristovao is on a distinguished road
Question

Need Help... A small problem with allocating memory


So this is my problem, I have this project to do for my programming class and we have to do it in C. And it is going to need a graphic presentation, however the teacher only accepts allegro, which I had to learn over the last 2 or 3 days. The program is supposed to be a simulation of the game of life, check out the following links for more info about it (if you wish):
http://mathworld.wolfram.com/CellularAutomaton.html
http://mathworld.wolfram.com/Life.html
So I'm going to need two matrixes, one to hold the actual configuration of the network, and one to hold the "evolution". However I made the program so that the user could choose the size of the network, these values are stored in info.grid_height and info.grid_width. Then I would have to allocate space in memory for these matrixes, set them up, and only then would I be able to use them. But after executing the following code, when I access the matrix, I get an error, Segmentation Fault. Which means I'm trying to access something that doesn't "belong" to the program.
CPP / C++ / C Code:
typedef struct INFO
{
    int grid_height;            /*Height of the matrix*/
    int grid_width;             /*Width of the matrix*/
} INFO;

static INFO info;

char ***Create_Matrix()     /*This function creates a "Triple matrix"*/
{
    int i, j;
    char ***matrix = NULL;
    
    if(info.file) Check_File();
    
    matrix       = (char ***)calloc(2,                                      sizeof(char **));   /*These three lines should allocate all the necessary space*/
    matrix[0]    = (char  **)calloc(2 * info.grid_width,                    sizeof(char  *));	/*If I multiply the first parameter by 4 it works*/
    matrix[0][0] = (char   *)calloc(2 * info.grid_width * info.grid_height, sizeof(char   ));	/*But I have to do it here to*/
    
    for(i = 0; i < 2; i++)                  /*These two cicles adjust all the pointers in the matrix*/
    {
        /*if(i != 0) matrix[i] = (char **)(matrix[i-1] + (sizeof(char *)*info.grid_width));*/
        matrix[i] = matrix[0] + i*info.grid_width*sizeof(char *);
        
        for(j = 0; j < info.grid_width; j++)
        {
            /*if(!(i == 0 && j == 0))
            {
                matrix[i][j] = (char *)(matrix[i][j-1] + (sizeof(char)*info.grid_height));
            }*/
            matrix[i][j] = matrix[0][0] + i*info.grid_width*info.grid_height*sizeof(char) + j*info.grid_height*sizeof(char);
        }
    }
    
    return matrix;
} 

When I access the matrix I make sure I don't go beyond it's boundaries. For the first index I'm in an infinite loop, and I use "%2" on the counter. On the next one I use a loop that only goes up to info.grid_width and inside that loop, I make another one that goes up to info.grid_height. Here's that code, it is where the error happens, but I think, it's because of one I allocate the memory.

CPP / C++ / C Code:
void Rand_Config(char **matrix)         /*This function creates a random configuration of 1s and 0s*/
{
    int i, j;
    
    srand(My_Time);                             /*reset rand for "more" random numbers*/
    for(i = 0; i < info.grid_width; i++)
        for(j = 0; j < info.grid_height; j++)
            matrix[i][j] = rand()%2;            /*place 1 or 0*/
    
    return;
}

When I call this function it's something like this:
Rand_Config(counter%2);

I think that is all the info needed, just one more thing, the struct INFO has many more variables, it's just simplified here.

I read that knowing my experience in programming would also be helpfull, so... I started programming about 5 years ago. I started with visual basic and I soon got fed up with it. So I moved on to C\C++ soon after. About two years ago, I had the bad idea of making a very very simple operating sistem, so I started to learn Assembly. Now I'm trying to learn PHP, and I'm still working on C++, and assembly. I'm not an expert at C\C++ but I can make nearly anything I put myself up to, sometimes with a few dificulties, but normally I'm able to solve them. So thankfor your help, and I'm a bit desperate, I have to hand in this project at the end of the week, and I've still got a few more bugs to solve!!!

One more thing, what in hell is allegro?!? I mean, I'd never heard of it before, and sincerely it's real bad. If only we could do the project in opengl, the only bummer is the windows interface in opengl and directX (which I've also started recently )!
Last edited by LuciWiz : 17-Jan-2007 at 02:57. Reason: Fixed code ending tag
  #2  
Old 17-Jan-2007, 07:33
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 6,148
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Need Help... A small problem with allocating memory


Quote:
Originally Posted by Cristovao
So this is my problem,

I don't believe that you posted the code that you are actually running.

It can't be compiled correctly since your struct INFO doesn't have a member named "file", and you use info.file for an INFO struct.

Or am I missing something?

Regards,

Dave
  #3  
Old 17-Jan-2007, 09:52
killzone killzone is offline
Junior Member
 
Join Date: Nov 2006
Posts: 66
killzone is an unknown quantity at this point

Re: Need Help... A small problem with allocating memory


why have you got

CPP / C++ / C Code:
***Create_Matrix()

do you really need the ***

the struct INFO does not have a File Function.

What are you testing for in the
CPP / C++ / C Code:
 for(info.file){} 
File is not a function or a member function of INFO struct.
So it wouldn't work.

You'd have to add a file function or a int file such as
CPP / C++ / C Code:
 int file; int file(); 

for the latter you have to change your IF loop to
CPP / C++ / C Code:
 if(info.file() = 0){} 


Or maybe I'm mistaken
  #4  
Old 17-Jan-2007, 13:58
Cristovao Cristovao is offline
New Member
 
Join Date: Jan 2007
Posts: 6
Cristovao is on a distinguished road

Re: Need Help... A small problem with allocating memory


Sorry, I messed things up.The correct structure is:
CPP / C++ / C Code:
typedef struct info
{
   int height;
   int width;
   int grid_height;
   int grid_width;
   int miliseconds;
   int generation;

   char limits;
   char file;
   char automate;
   char draw;
   char rand;
}

I had the code divided in several files and I sent an initial structure which I used just for testing. All the variables are information which the user can enter in a menu, the ones with type char are to be used as bools, in the version of c my teacher makes me use there aren't any bools, I believe it is ISO C 90.
sorry again!
and thanks for the help, and i still haven't corected the mistake I mentioned before!!!!
  #5  
Old 17-Jan-2007, 15:17
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 6,148
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Need Help... A small problem with allocating memory


Quote:
Originally Posted by Cristovao
The correct structure is:
.
.


You are going to have something that allow you to access the individual chars as matrix[i][j][k]

I think, from your code that the first index will have two values: 0, 1
The second index will have grid_height values: 0, 1, ... grid_height-1
The third index will have grid_width values: 0, 1, ... grid_width-1.

In other words, the notation will suggest two 2-D matrices. Each has grid_height rows and grid_width columns. If your visualization is different, than you can adjust the following narrative to suite your purposes.

The variable matrix has type char ***.
So far so good.

Here's the way that I look at it: Each element of matrix will be a pointer to something that will be treated notationally as a 2-D matrix. So I think of the 3-D matrix as an array of 2-D matrices.

The variable notation matrix[0] will be treated as a "pointer to pointer to char" and matrix[1] will be a "pointer to pointer to char".
You will have to allocate storage for two "pointer to pointer to char" and set matrix[0] and matrix[1] to the addresses furnished to you by calloc.

Now, matrix[0][0] will be a pointer to char, matrix[0][1] will be a pointer to char, ...
That is, each element matrix[i][j] will be a pointer to something that will be treated notationally as an array (a 1-D matrix, if you will). In each 3-D matrix, we will have a number of these pointers equal to the number of rows of the 2-D matrices.
Then, for each element matrix[i][j] (that is, for each row of each 2-D matrix) we will allocate an amount of storage equal to the number of columns of each 2-D matrix.

Your function could look like:
CPP / C++ / C Code:
char ***Create_Matrix(void)
{
    /*This function creates a "Triple matrix" */
    /* will access matrix elements bi matrix[i][j][k] */
    int i, j;

    char ***matrix;

    /* Allocate storage for two pointers
     * Each pointer will point to a 2-d array
     * Note that for C programs, the cast in front of calloc
     * is neither required or recommended for general use.
     * (For a number of subtle reasons)
     * For C++ programs I think it's better to use new/delete
     * rather than calloc/free, but I'll leave things the
     * way you had them
     */
    matrix = (char ***) calloc(2, sizeof(char **));

    /* Each member of the 3-D matrix is treated as a 2-D matrix
     * (actually a pointer to char*).
     *
     * Allocate storage for a number of pointers equal to
     * the number of 2-D matrices
     *
     * Then for each 2-D matrix, allocate storage for a number
     * of pointers equal to the number of rows.
     *
     * Then for each row, allocate storage for the number of chars
     * in each row.
     */
    for (i = 0; i < 2; i++) { /* two 3-D matrices */
        matrix[i] = calloc(info.grid_height, sizeof(char *));
        for (j = 0; j < info.grid_height; j++) {
            matrix[i][j] = calloc(info.grid_width, sizeof(char));
        }
    }
    /* note that sizeof(char) is always 1, but I left it in place
     * just for the heck of it
     */

    /* note that the total number of chars allocated for matrix
     * elements is equal to
     * two times the grid height times the grid width
     */
    return matrix;
}

I would probably not use a file scope variable for the info matrix; I would probably make it a parameter of the function (or at least use the row and column sizes as parameters rather than using "global" parameters).

Something like:

CPP / C++ / C Code:
char ***Create_Matrix(INFO *inf)
{
.
.
.
    for (i = 0; i < 2; i++) { /* two 3-D matrices */
        matrix[i] = calloc(inf->grid_height, sizeof(char *));
        for (j = 0; j < inf->grid_height; j++) {
            matrix[i][j] = calloc(inf->grid_width, sizeof(char));
        }
    }
.
.
.

As noted in the comments, if this is a C++ program I probably wouldn't use calloc either, but it's not necessarily "wrong" to do so. If I did use calloc (or malloc) I would probably test the return value each time to make sure the allocation was successful.


Regards,

Dave
 
 

Recent GIDBlogGID Spam Detector 1.1.0 by gidnetwork

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Pipeline freeze simulation darklightred C++ Forum 6 27-Jul-2006 19:37
Memory de-allocation during debugging gaoanyu C Programming Language 12 19-Dec-2005 04:50
Pointer Usage in C++: Beginner to Advanced varunhome C++ Forum 0 19-Aug-2005 09:25
[Tutorial] Pointers in C (Part I) Stack Overflow C Programming Language 1 08-Apr-2005 18:35
Small problem Krc784 C++ Forum 1 05-Nov-2004 08:34

Network Sites: GIDNetwork · GIDApp · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 20:18.


vBulletin, Copyright © 2000 - 2013, Jelsoft Enterprises Ltd.