How to save the scanf input only if there's enough space in the array? How to reallocate array to let the scanf input fits in?
问题 #include <stdio.h> int main() { char *mystring = calloc(2, sizeof(char)); scanf("%10[^\n]s", mystring); printf("\nValue: %s\nSize of array: %d\nAllocated space: %d\n", mystring, 2 * sizeof(char), sizeof(char) * strlen(mystring)); free(mystring); } Output: $ ./"dyn_mem" laaaaaaaaaaa Value: laaaaaaaaa Size of array: 2 Allocated space: 10 This code can produce an undefined behavior if I enter in the scanf input a string bigger than array size. How can I handle this ? 回答1: There are multiple