I'll be honest, I'm a complete novice at c. Thus, things like malloc and realloc are alien concepts. I think I have the basics down, but I just can't quite get there 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);
}
It's reading from terminal - cat file | ./program and is just a bunch of words of arbitrary length. I'm trying to get them all into an array (array).
Edit: I should mentino that I'm apparently trying to access memory I didn't allocated: 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
while (int args = scanf("%s", string))does this really compile on your system?stringandarraywould help...this (array = (char *) malloc(strlen(string));) is probably wrong; most likely it should bearray = malloc(sizeof(*array));which avoids me having to know the type ofarrayand still gets the answer right. If you really are allocating achar *, then you almost certainly needstrlen(string)+1to allow for the null termination byte. Your code doesn't look wholly consistent. If you need an array of strings, you need both an array of characters pointers, and the pointers to each string:char **array = 0;but…