2

i'm having a problem when trying to write the second row of the matrix (segfault exc_bad_access and kern_invalid_address) allocated with the following function:

Here is my alloc function:

int amatrix(char*** m, const int i, const int j) 
{

    int k;

    (*m) = (char**) malloc(sizeof(char*) * i);
    if ((*m) == NULL) {
        return ERROR;
    }

    for (k = 0; k < i; k++) {
        (*m)[k] = (char*) malloc(sizeof(char) * j);
        if ((*m)[k] == NULL) {
            return ERROR;
        }
    }

    return SUCCESS;
}

I call it by using:

char** matrix;
if (amatrix(&matrix, i, j)) { ...

Edit: As requested:

#define ERROR 00
#define SUCCESS 01

The access where the trouble is:

int gmatrix(char*** m, const int i, const int j)
{
int k, l;

for (k = 0; k < i; k++) {
    for (l = 0; l < j; l++) {
        printf("Matrix[%d][%d] = ", k, l);
        scanf(" %c", m[k][l]);
    }
}

return SUCCESS;
}

Thank you for the quick replies!

bellati
  • 82
  • 1
  • 9

1 Answers1

2

Your gmatrix function should take m as a char** parameter, not char***, because it does not need to change its value like amatrix does (only what it points to).

Then you should change the scanf call to:

scanf(" %c", &m[k][l]);

Your current code (with char*** m) doesn't work because m[k] will give undefined behavior when k!=0, because m points only to a single char**.

If m is a char***, the scanf call would need to look like:

scanf(" %c", &(*m)[k][l]);
interjay
  • 107,303
  • 21
  • 270
  • 254
  • tyvm, it worked! I wasn't aware of the undefined behavior, could you explain more? Why it's undefined when k != 0? – bellati Nov 07 '12 at 16:25
  • @bellati: Suppose you have `int a; int *p = &a`. Then `p[0]` is OK but `p[1]` is undefined because `p` only points to one `int`. The same is true here, except you have `char**` instead of `int`. – interjay Nov 07 '12 at 16:29
  • Nice, now I understand. How about a freematrix function? Does free needs to modify the address or only what the matrix points to? Also is there any way to test if something has been freed? Tyvm in advance! – bellati Nov 07 '12 at 17:34
  • @bellati: For `free` you don't need to modify the address. And there is no way to test if a pointer has been freed. – interjay Nov 07 '12 at 19:56