C language string memory allocation note, string allocation note
I. Questions
There is a question:
#include "stdio.h"int main(){ char word1[8]; char word2[8]; scanf("%s", word1); scanf("%s", word2); printf("word1=%s##word2=%s\n", word1, word2); return 0;}
Run the code and enter:
1234567812345678
Why is the output:
word1=##word2=12345678
Where does word1 go.
Ii. Analysis
Because local simple variables in C language exist in the stack, the stack is advanced and later, so the variables first defined are at the bottom of the stack. After word1 is input, the variables in the memory are as follows:
We can see that B8 is out of the range of character arrays defined by word1.
When word2 is input, the memory changes to the following:
Because only 8 address spaces are provided between A8 and AF (because the end mark \ 0 of the last string is to be placed, A8 can only be used to AE ), but the input is 8 characters, so the end mark of the string is written to the next memory address (in B0 ).
Iii. Verification
#include "stdio.h"int main(){ char word1[8]; char word2[8]; scanf("%s", word1); scanf("%s", word2); int count = 8; int i; printf("\nword1 begin addr = %p\n", word1); for(i=0;i<count;i++) { printf("word1[%d]=%c addr=%p\n", i, word1[i], &word1[i]); } printf("\n-------------------------------\n"); printf("word2 begin addr = %p\n", word2); for(i=0;i<count;i++) { printf("word2[%d]=%c addr=%p\n", i, word2[i], &word2[i]); } printf("\n-------------------------------\n"); printf("word1=%s##word2=%s\n", word1, word2); printf("0x0028FEB8=%c\n", *(int*)0x0028FEB8); return 0; }
Running effect: