Valgrind 说尝试访问动态数组时未分配内存

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

我在调用 save_ADD 函数时遇到以下代码问题。如果我输入

,Valgrind 不会 return 任何东西
steps[count].what= 'A';
steps[count].letter = (char)character;

函数内部 sequence。但是当它在一个单独的函数中时,它会说:

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)

这是我的代码:

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;
}

我不太明白为什么在这种情况下没有分配内存。

同定义

instruction *steps=NULL;

您将 steps 定义为 instruction 结构数组 objects.

但稍后在 save_ADD 中,您将 &steps 视为指向 instruction 结构对象的 指针数组

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

解决方法是不传递指向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);