在调用save_ADD
函数时,以下代码有问题。如果我放,Valgrind什么都不回
steps[count].what= 'A';
steps[count].letter = (char)character;
在函数CCD_ 2内部。但当它在一个单独的功能中时,它会说:
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
结构对象的数组。
但稍后在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);