#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char string[] = "october"; // 7 letters
strcpy(string, "september"); // 9 letters
printf("the size of %s is %d and the length is %d\n\n", string,
sizeof(string), strlen(string));
return 0;
}
Output:
$ ./a.out
the size of september is 8 and the length is 9
Is there something wrong with my syntax or what?
string. This is undefined behavior.stringcan only hold 8 characters (7 for "october" and 1 for the null terminator). When you callstrcpy, you are writing 10 characters to it (9 for "september" and 1 for the null terminator), which means you have gone past the end of the array and are overwriting the adjacent memory. - Marlonsizeofis calculated at compile time where asstrlenis run time. - Naveenint foo(int n) { int a[n];the valuesizeof ais not calculated at compile-time. - caf