我经常想做一些类似下面的代码示例。在main()中的free会导致一个错误,通常。错误的开头是:"Error in `.stackoverflow': free(): invalid: "Error in `.stackoverflow': free(): invalid next size (normal): ... "等等。Googling提示我,我可能已经超过了malloced块的限制,或者类似的东西。不幸的是,Valgrind的输出对我来说仍然是模糊的。
我到底做错了什么?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct letter {
char alpha;
int value;
};
struct letter* init_table() {
//struct letter* table = calloc(27, sizeof(struct letter));
struct letter* table = malloc(27 * sizeof(struct letter));
table[0].alpha = ' ';
table[0].value = 1;
for (int j = 1; j <= 27; j++) {
table[j].alpha = (char) (j + 64);
table[j].value = j+1;
}
return table;
}
int main(int argc, char **argv) {
struct letter *table = init_table();
for (int j = 0; j < 27; j++) {
printf("char is %c and int is %d\n",table[j].alpha, table[j].value);
}
free(table);
return 0;
}
for (int j = 1; j <= 27; j++)
这里你需要把 j<27
.