C and C++ commonly used functions are prone to wrong point analysis

  • 2020-04-02 02:39:20
  • OfStack

This paper simply analyzes the error prone points of commonly used functions in C/C++, including memset, sizeof, getchar and other functions. Share with you for your reference. Specific analysis is as follows:

1. Memset

#include <string.h>
void* memset( void* buffer, int ch, size_t count );

Set the contents of the first count bytes of the buffer in memory to the ASCII value specified by ch. It is often used to initialize the array. When copying in bytes, if the buffer is an int long, or other types of pointer, it should not be the sizeof the array, it should be the sizeof the array *sizeof(type).

sizeof(buffer)//Buffer is an array

2. The sizeof

Returns the size of the type in bytes.
It's different for arrays and Pointers.

int *p=new int[5]; 
int q[5]={0}; 
delete[] p;

The output values are different.
Sizeof (p):p is the pointer and outputs the sizeof the pointer type, 64/8=8 on 64-bit
Sizeof (q):q is an array of type int, which outputs the number of bytes in the array.4*5=20.

3. The getchar

#include <stdio.h>
int getchar( void );

Getchar returns an integer instead of a char if the following code appears.

char c;

Where c is part of the truncated int,c may not hold all characters, especially EOF.
The likelihood of an outcome,

1) some characters are the same as EOF after truncation, causing the program to terminate normally when running

2) get stuck in a loop

3) some compilers do truncate c, but when compared, the return value of getchar is compared to EOF, causing the program to appear to be "running normally"

Hope that the article described in the C/C++ programming to help you.

Related articles: