C language string memory allocation note, string allocation note

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.