12 interesting C-language quiz (detailed)

Source: Internet
Author: User

This article refers to the blog "12 interesting C language question and answer", on the basis of the original text added to the corresponding point of knowledge detailed introduction.

1 gets () method

Q: The following code has a hidden problem, can you find it?

1#include <stdio.h>2 3 intMainvoid)4 {5     Charbuff[Ten];6memset (Buff,0,sizeof(Buff));7 gets (buff);8printf"%s\n", buff);9 Ten     return 0; One}

A: This inconspicuous problem is the use of the Gets () method, whose function prototype is as follows:

Char* gets (char *s);

This method accepts a character array parameter, but does not check if the array has enough space to copy the data. The Get () function is unsafe and deprecated, and in general the compiler gives a warning: the ' get ' function is dangerous and should not being used. Gets () does not check whether the reserved store can accommodate the data that is actually entered. The extra characters simply overflow into the adjacent storage area, which can cause errors.

So, here we generally use the fgets () method better, the function prototype is as follows:

Char* fgets (charint

The fgets () function is generally used to read the n-1 characters in the file into s , in fact, this function has a good use is to read the string from the standard input stream, And do not worry about the number of characters entered beyond the size of the character array, causing overflow problems! How do you do it? As follows:

Char str[];  

It is worth noting that: remember that fgets () reads only n-1 characters . therefore,fgets () reads the newline character, the end of the file, or the n-1 characters that are returned.

12 interesting C-language quiz (detailed)

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.