老实说,我是c的新手。因此,像 malloc 和 realloc 这样的东西是陌生的概念。我想我已经掌握了基础知识,但我不能完全做到 100%。
while (int args = scanf("%s", string)) {
if (args < 0) break;
count++;
if (array == NULL) {
array = (char *) malloc(strlen(string));
if (array == NULL) {
printf("Error allocating memory");
exit(1);
}
} else {
printf("%s %d\n", string, strlen(string));
array = (char *) realloc(array, (sizeof(array) + strlen(string) + 1));
if (array == NULL) {
printf("Error allocating memory");
free(array);
exit(1);
}
printf("%lu\n", sizeof(array));
}
strcpy(&array[count - 1], string);
}
它正在从终端读取 - cat 文件 | ./program 只是一堆任意长度的单词。我正在尝试将它们全部放入一个数组(数组)中。
编辑:我应该提到我显然试图访问我没有分配的内存:malloc: *** error for object 0x7fe9e04039a0: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Segmentation fault: 11