C-language string memory allocation small note

Source: Internet
Author: User

First, the question

Have such a problem:

#include"stdio.h"intMain () {Charword1[8]; Charword2[8]; scanf ("%s", word1); scanf ("%s", Word2); printf ("word1=%s# #word2 =%s\n", Word1, Word2); return 0;}

Run the code and enter:

12345678 12345678

After that, why the output is:

word1=# #word2 =12345678

Where's word1?

Second, analysis

Since the C language local simple variable is present in the stack, the stack is advanced, so the variables defined first are at the bottom of the stack. After entering Word1, the in-memory variables are as follows:

As we can see, B8 has exceeded the range of character arrays defined by Word1.

When Word2 is entered, the in-memory variable becomes this:

Since only A8 to AF a total of 8 address space (because the last one to put the string end flag, so the actual can only use A8 to AE), but entered 8 characters, so that the end of the string is written to the next memory address (that is, B0).

Third, verification
#include"stdio.h"intMain () {Charword1[8]; Charword2[8]; scanf ("%s", word1); scanf ("%s", Word2); intCount =8; inti; 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; }

Operating effect:

C-language string memory allocation small note

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.