Search code examples
cpointersstrcpy

C triple pointers: Unable to copy string into position triplepointer[x][y] with [x] being greater than 1


I'm trying out triple pointers for the first time. This question is where I got the info on how to allocate a triple pointer and this is how the triple pointer has been allocated:

//In this case size will always be 4
int size = countLines(file);
printf("size: %d\n", size);
char*** tripleptr = malloc(sizeof(*tripleptr)*size);
int i = 0, k = 0, j = 0;
for(; i < size; i++){
    tripleptr[i] = malloc(sizeof(*(tripleptr[i]))*size);
    for(; k< size; k++){
        tripleptr[i][k] = malloc(sizeof(*(tripleptr[i][k]))*512);
    }
}

If I try to copy a string literal into position [0][0] like this

strcpy(tripleptr[0][0], "something");

it works perfectly (same thing for [0][1] to [0][3]), but

strcpy(tripleptr[1][0], "something");

doesn't (it makes the program go into Segmentation Fault). What is it that could be causing such a weird behavior? I can't find any indexing mistake in the memory allocation part


Solution

  • The problem is in your loops:

    int i = 0, k = 0, j = 0;
    for(; i < size; i++){
        tripleptr[i] = malloc(sizeof(*(tripleptr[i]))*size);
        for(; k< size; k++){
            tripleptr[i][k] = malloc(sizeof(*(tripleptr[i][k]))*512);
        }
    }
    

    You initialized i and k before entering the nested loop, but you don't reset k when the inner loop restarts on the next iteration. This means that you only allocated memory for the first row of strings. So tripleptr[1][0] is uninitialized, and dereferencing that pointer gives you undefined behavior.

    Explicitly initialize youf loop control variables each time:

    int i, k;
    for(i=0; i < size; i++){
        tripleptr[i] = malloc(sizeof(*(tripleptr[i]))*size);
        for(k=0; k< size; k++){
            tripleptr[i][k] = malloc(sizeof(*(tripleptr[i][k]))*512);
        }
    }