*sigh* Malloc get's me every time...

Basically what I'm trying to do is read data from a file to populate a square array on integers.

I'm declaring the array as 'int** matrix' in main(). I pass this to the function which handles reading the file (the parameter for the function is also of type int**).

In that function, I load the data from the file, figure out how large the array has to be and then initiate the array. I do that as follows:

matrix = malloc(size * sizeof(int*));
        
        for (i = 0; i < size; i++)
        {
            matrix[i] = malloc(size * sizeof(int));
        }

I then go ahead and populate the array and print out the results in the function which works fine.

However this doesn't work for some reason. When I try to print the array back in main(), my program is segfaulting.

Any ideas?

Recommended Answers

All 10 Replies

What does your print function look like?
Take a look at this.

You could create an access function and allocate an array[ size * size * SIZEOF(int) ];
And use a row,column access function.

OR

Use calloc( sizeof(int) * SIZE, sizeof(int) * SIZE )

Hmm, I don't those are helping too much.

I ran a debugger and this is what I concluded.

When I pass in the the int** to the function I want to create it in, the address of it 0x1000. However, once I call the first malloc (matrix = malloc(size * sizeof(int*))) the address it points to changes (i.e. 0x100480).

When I exit the function, however, the original int** array still points to 0x1000.

How can I remedy this?

Hmm, I don't those are helping too much.

I ran a debugger and this is what I concluded.

When I pass in the the int** to the function I want to create it in, the address of it 0x1000. However, once I call the first malloc (matrix = malloc(size * sizeof(int*))) the address it points to changes (i.e. 0x100480).

When I exit the function, however, the original int** array still points to 0x1000.

How can I remedy this?

It's rather hard for us to debug a function without ever seeing it. Check to see that you don't accidentally write to 'matrix' instead of '*matrix' (or '*matrix[]').
Good luck.

You really need to post the entire code for us to understand your problem. Pointer declaration, allocation looked okay, access thus usage!

I'm a bit hesitant to post the code because it's for an assignment.

Nonetheless, I'll change it a bit and put it up here.

Here's the code in main():

//This is the array
  int** matrix = NULL;
    
//This function loads the data from the file and returns the size of the 2d array (it's a square array)
    size = readFromFile(matrix, filename);
    
//This prints out the 2d array
    for (i = 0; i < size; i++)
    {
        for (j = 0; j < size; j++)
        {
                printf(" %d", matrix[i][j]);
        }
        printf("\n");
    }

This is the actual code which reads the file (inside the readFromFile function):

matrix = malloc(size * sizeof(int*));
//Perform check
        
        for (i = 0; i < size; i++)
        {
            matrix[i] = malloc(size * sizeof(int));

//Perform check
        }
        
//Set array values to 0
        for (i = 0; i < size; i++)
        {
            for (j = 0; j < size; j++)
            {
                matrix[i][j] = someRandomNumber();
            }
        }

	return size;

That's basically it. It seems that the matrix (int** matrix) is being passed by value; therefore when I play with it in the function, it's changing a different memory location so the original remains unchanged. How can I solve this?

The allocations really should be...

matrix = (int **)malloc(size * sizeof(int*));
//Perform check
        
        for (i = 0; i < size; i++)
        {
            matrix[i] = (int *)malloc(size * sizeof(int));

Other then that, I don't see anything wrong with the snippets you've posted!

It seems that the matrix (int** matrix) is being passed by value; therefore when I play with it in the function, it's changing a different memory location so the original remains unchanged. How can I solve this?

Either return matrix or pass a pointer to it as a parameter to this called function.

Thanks for all the help guys.

I got it working by returning the address to matrix however this isn't an ideal solution as I'd like to have the size of matrix as the return value. It's not a big deal though, and I can push on for the moment.

However, if possible, I would like to go back and make the function edit matrix without needing to return it's address.

What I tried was to pass a reference to matrix (&matrix - a reference to int**) and then edit it inside the code.

e.g.
*matrix = malloc(......);

However, when I do stuff like *matrix[j] = someRand() I get a compile error regarding an invalid unary operator.

If a reference to int** is the correct way to solve this, how should I go about working with the int*** object inside the function code?

Again, thanks for the help.

I got it working by returning the address to matrix however this isn't an ideal solution as I'd like to have the size of matrix as the return value.

Why, may I ask? Is size determined in the called function? If it is passed as a parameter, why wouldn't the calling function already not know size ?

Regarding the alternative, I think it may need to be like

(*matrix)[i][j] = someRand();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.