Search code examples
cmemorymemory-leaksmallocvalgrind

Valgrind says that memory is not allocated when trying to access dynamic array


I have a problem with the following code while calling the save_ADD function. Valgrind doesn't return anything if I put

steps[count].what= 'A';
steps[count].letter = (char)character;

inside the function sequence. But when it's in a separate function, it says:

Invalid write of size 1
==14679==    at 0x109273: save_ADD 
==14679==    by 0x1092FE: sequence 
==14679==    by 0x109345: main 
==14679==  Address 0x69bfa4a127c89400 is not stack'd, malloc'd or (recently) free'd
==14679== 
==14679== 
==14679== Process terminating with default action of signal 11 (SIGSEGV)
==14679==  General Protection Fault
==14679==    at 0x109273: save_ADD 
==14679==    by 0x1092FE: sequence 
==14679==    by 0x109345: main 
Segmentation fault (core dumped)

Here's my code:

struct instruction {
    char what;
    char letter;
};
typedef struct instruction instruction;

int more(int n) {
    return 1 + 2 * n;
}

void allocate_steps(instruction **steps, int *size) {
    *size = more(*size);
    *steps = realloc(*steps, (size_t) (*size) * sizeof(**steps));
}

void sizeup(instruction **steps, int *size, int count) {
    while (count >= *size)
    {
        allocate_steps(steps, size);
    }
}

void save_ADD(instruction **steps, int index, char character) {
    steps[index]->what= 'A';
    steps[index]->letter = character;
}

void sequence() {
    int character = getchar();
    instruction *steps=NULL;
    int size = 0;
    int count = 0;
    while (character != EOF) {
        {
            sizeup(&steps, &size, count);
            save_ADD(&steps, count, (char)character);
           // steps[count].what= 'A';
           // steps[count].letter = (char)character;
            count++;
        }
        character = getchar();
    }
    free(steps);
}
int main() {
    sequence();
    return 0;
}

I don't really understand why the memory is not allocated in this case.


Solution

  • With the definition

    instruction *steps=NULL;
    

    you define steps as an array of instruction structure objects.

    But later in save_ADD you treat &steps as an array of pointers to instruction structure objects:

    steps[index]->what= 'A';
    

    The solution is to not pass a pointer to the pointer to save_ADD:

    void save_ADD(instruction *steps, int index, char character) {
        steps[index].what= 'A';
        steps[index].letter = character;
    }
    
    ...
    
    save_ADD(steps, count, (char)character);