当前位置:网站首页>Dynamic memory management, file operation, preprocessing
Dynamic memory management, file operation, preprocessing
2022-04-22 06:11:00 【Birds follow February】
Table of contents title
Dynamic memory management
Apply for memory by creating variables . When to free memory , It depends on what kind of variable the variable is .
If it's a global variable , Just follow the program to release .
If it's a static variable , Also follow the program to release .
If it's a local variable , Just follow the code block to release .
1. Dynamic memory management , Be able to decide the application time and release time more flexibly ~
2. Dynamic memory management can determine the size of memory requests at run time ~
malloc
void* malloc (size_t size);
//size Number of bytes , The compiler only knows the starting address of memory ,
// I don't know the size , Apply for continuous memory ,
// Under normal circumstances, check whether the application is successful ( Unsuccessful return NULL)

Use
#include<Windows.h>
#include<stdio.h>
#include<stdlib.h>
int main(){
int* p = (int*)malloc(4);
*p = 10;
printf("%d\n", *p);
// Put this 40 A byte is understood as a length 10 An element of int Array
// p As the starting element address of the array .
int* p = (int*)malloc(10 * sizeof(int));
for (int i = 0; i < 10; i++) {
p[i] = 0;
}
system("pause");
return 0;
}
Release time
1. If the program ends , It was released with the program .
2. When the program is not over , Manual call free , And then it's released .
free
void free (void* ptr);//ptr maolloc Return address , Can handle NULL
Use
#include<Windows.h>
#include<stdio.h>
#include<stdlib.h>
int main(){
// Put this 40 A byte is understood as a length 10 An element of int Array
// p As the starting element address of the array .
int* p = (int*)malloc(10 * sizeof(int));
for (int i = 0; i < 10; i++) {
p[i] = 0;
}
free(p);
system("pause");
return 0;
}
stay C++ Inside , Introduced " Intelligent pointer ”, Can solve the problem of memory leakage to a certain extent . Take advantage of C++ Medium RAlI Mechanism ~ Before the function exits , Perform some logic .
You can put the free The operation is put into such logic ~
Java / Python, Garbage collection mechanism is introduced , Can better solve the problem of memory leakage .
Memory recycling does not have to be manually recycled by the program , It's inside the program , There is special logic to scan regularly , See which memory can be released at present, and then it will be released automatically .
calloc
void* calloc (size_t num, size_t size);
Use
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p = (int*)calloc(10, sizeof(int));
if(NULL != p)
{
// Use space
}
free(p);
p = NULL;
return 0; }
calloc Requested memory , Will be initialized to full 0.
malloc Requested memory , Is not initialized , The values in memory are random values .
realloc
realloc expansion , It also depends on whether there is enough free space in the back ~ If there's enough space in the back , Just break through the wall , Directly use the space behind .
If there's not enough space in the back , Just find a bigger space , Carry it as a whole ~
void* realloc (void* ptr, size_t size);
Use
#include <stdio.h>
int main()
{
int *ptr = (int*)malloc(100);
if(ptr != NULL)
{
// Business processing
}
else
{
exit(EXIT_FAILURE);
}
// Expand capacity
// Code 1
ptr = (int*)realloc(ptr, 1000);// Is this ok? ?( What happens if the application fails ?)
// Code 2
int*p = NULL;
p = realloc(ptr, 1000);
if(p != NULL)
{
ptr = p;
}
// Business processing
free(ptr);
return 0; }
The three difference
identical : They all apply for space from the heap , Finally, it needs to be used free Release , The return value types are void*, When in use, strong rotation and air judgment are required
malloc: The meaning of the parameter indicates the number of bytes required to apply for space
calloc: 1. Parameters : Parameters 1–> Number of elements parameter 2–> Number of bytes occupied by type
2. function : Apply for space from the heap & Each byte in the space is initialized to 0
realloc(void* p. int newsize):
p It's empty : Equivalent to malloc
p Not empty : realloc Will p Adjust the pointing space to newsize Bytes
Common memory errors
void test()
{
int *p = (int *)malloc(INT_MAX/4);
*p = 20;// If p The value of is NULL, There will be problems
free(p);
}
void test()
{
int i = 0;
int *p = (int *)malloc(10*sizeof(int));
if(NULL == p)
{
exit(EXIT_FAILURE);
}
for(i=0; i<=10; i++)
{
*(p+i) = i;// When i yes 10 Cross border visits when
}
free(p);
}
void test()
{
int a = 10;
int *p = &a;
free(p);// Only dynamically requested memory is released
}
void test()
{
int *p = (int *)malloc(100);
p++;
free(p);//p No longer points to the start of dynamic memory
}
void test()
{
int *p = (int *)malloc(100);
free(p);
free(p);// Repeat release
}
void test()
{
int *p = (int *)malloc(100);
if(NULL != p)
{
*p = 20;
}// Memory leak
}
int main()
{
test();
while(1);
}
Common questions
1.
void GetMemory(char *p) {
p = (char *)malloc(100);
}
void Test(void) {
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
1. Memory leak . malloc No, free
2. malloc After that, it is not determined that the return value is NULL
3.GetMemory Functions cannot be modified str. Value ~str Still NULL. In the back strcpy, There will be problems ~
2.
char *GetMemory(void) {
char p[] = "hello world";// Local variables are released as the function is released
return p; }
void Test(void) {
char *str = NULL;
str = GetMemory();// The memory referred to by the local variable has been released
printf(str);
}
3.
void GetMemory(char **p, int num) {
*p = (char *)malloc(num);
}
void Test(void) {
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
1. Memory leak . malloc No, free
2. malloc After that, it is not determined that the return value is NULL
4.
void Test(void) {
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}

The memory area of a program
linux in


The stack size can be configured ( commonly 1m)
linux Modify stack size

file
classification
Ordinary documents : text file , Binary
Directory file
Correlation function
io Functions are all in stdio.h Contained in the
FILE Structure
Used to describe a file ~
The file is on disk . To operate the disk directly , It's not so easy . So the operating system is encapsulated .
When opening a file , In fact, it creates a variable in memory (FILE Structural variable ), This variable is associated with the file on the disk . read / Write this variable , It's equivalent to reading and writing files .
fopen
// Open file
FILE * fopen ( const char * filename, const char * mode );
// Parameter file path , The latter is opened by

Use
#define _CRT_SECURE_NO_WARNINGS
#include<Windows.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(){
/* fp => file pointer The file pointer If opening the file fails , It will return NULL. If the file does not exist or does not have read and write permissions , Will fail .*/
FILE* fp = fopen("E:/test.txt", "r");
if (fp == NULL) {
printf(" fail to open file ! Error code : %s\n", strerror(errno));//error A macro definition represents an error
system("pause");
return 0;
}
printf(" File opened successfully ! fp=%p\n", fp);
system("pause");
return 0;
}

#include <stdio.h>
#include <string.h>
int main(){
FILE* fp = fopen("1.txt", "w+");
if(fp == NULL){
printf("fopen open file failed\n");
//errno -> An error code in the system
// When we call a function , If the function goes wrong , Will give errno The assignment becomes the corresponding error code ( integer )
//errno --> error msg
//perror -》 error msg Print out , Will go straight to get errno Analyze the value in , After parsing , Print ;
//void perror(const char *s);
// 76 class - NO SUCH FILE or dir
perror("fopen:");
return 0;
}
// The file was opened successfully
printf("fopen open file success\n");
// Write the test
const char* content = "76-linux so easy";
size_t w_size = fwrite(content, 2, 8, fp);
printf("w_size = %ld\n", w_size);
fseek(fp, 3, SEEK_SET);
// Test reading
char buf[1024] = {
0};
size_t r_size = fread(buf, 1, sizeof(buf) - 1, fp);
printf("r_size = %ld\n", r_size);
printf("buf = %s\n", buf);
// If you don't close the file stream pointer , It will cause the disclosure of file handle
fclose(fp);
return 0;
}
strerror
Return error code , The corresponding error message .
char * strerror ( int errnum );
Use
#include <stdio.h>
#include <string.h>
#include <errno.h>// The header file that must be included
int main ()
{
FILE * pFile;
pFile = fopen ("unexist.ent","r");
if (pFile == NULL)
printf ("Error opening file unexist.ent: %s\n",strerror(errno));
//errno: Last error number
return 0; }
fclose
// Close file
int fclose ( FILE * stream );
Use
#include <stdio.h>
int main ()
{
FILE * pFile;
// Open file
pFile = fopen ("myfile.txt","w");
// File operations
if (pFile!=NULL)
{
fputs ("fopen example",pFile);
// Close file
fclose (pFile);
}
return 0; }
fread
How to read data : Byte stream and datagram
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
//*ptr The memory address where the content is read , Returns the number of successful reads
Use
#define _CRT_SECURE_NO_WARNINGS
#include<Windows.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(){
/* fp => file pointer The file pointer If opening the file fails , It will return NULL. If the file does not exist or does not have read and write permissions , Will fail .*/
FILE* fp = fopen("E:/test.txt", "r");
if (fp == NULL) {
printf(" fail to open file ! Error code : %s\n", strerror(errno));//error A macro definition represents an error
system("pause");
return 0;
}
printf(" File opened successfully ! fp=%p\n", fp);
char buffer[10] = "1111" ;
fread(buffer, 1, 8, fp);
printf(buffer);
system("pause");
return 0;
}
fwrite
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
Use
#define _CRT_SECURE_NO_WARNINGS
#include<Windows.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(){
/* fp => file pointer The file pointer If opening the file fails , It will return NULL. If the file does not exist or does not have read and write permissions , Will fail .*/
FILE* fp = fopen("E:/test.txt", "w");
if (fp == NULL) {
printf(" fail to open file ! Error code : %s\n", strerror(errno));//error A macro definition represents an error
system("pause");
return 0;
}
printf(" File opened successfully ! fp=%p\n", fp);
char buffer[10] = "1111" ;
fwrite(buffer, 1, 4, fp);
printf(buffer);
system("pause");
return 0;
}
Other sequential reading and writing

EOF
If a file has been read , Then continue trying to read , It will read EOF.
EOF ' It's actually -1, Not one ascii Characters in code table . Just use -1 This data represents the completion of file reading .
sscanf and sprintf
//sscanf Parse a content from a string .
//sprintf Output a formatted result to a string .
char* str = "num = 10";
int num = 0;
sscanf(str, "num = %d", &num);
printf("%d\n", num);
char str[1024] = {
0 };
sprintf(str, "num = %d", 10);
printf(str);
A particularly important usage :// For strings and numbers ( Integers / Floating point numbers ) Switch between ~
// Convert a string to an integer , Use sscanf
char* str1 = "10";
char* str2 = "20";
// Here I want to calculate the sum of these two values ~
int num1 = 0;
// This is the time to put str1 Extract the content from the , Into the int
sscanf(str1, "%d", &num1);
int num2 = 0;
sscanf(str2, "%d", &num2);
int result = num1 + num2;
printf("result = %d\n", result);
// Convert an integer to a string , Use sprintf
int num = 100;
char buffer[1024] = {
0 };
sprintf(buffer, "%d", num);
printf("%s\n", buffer);
Conversion of integer and string atoi iota

#define _CRT_SECURE_NO_WARNINGS
#include<Windows.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h> /* atoi */
int main ()
{
int i;
char buffer[256];
printf("Enter a number: ");
fgets(buffer, 256, stdin);
i = atoi(buffer);
printf("The value entered is %d. Its double is %d.\n", i, i * 2);
system("pause");
return 0;
}
char * itoa ( int value, char * str, int base );
#define _CRT_SECURE_NO_WARNINGS
#include<Windows.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h> /* atoi */
int main ()
{
int i;
char buffer[33];
printf("Enter a number: ");
scanf("%d", &i);
_itoa(i, buffer, 10);
printf("decimal: %s\n", buffer);
_itoa(i, buffer, 16);
printf("hexadecimal: %s\n", buffer);
_itoa(i, buffer, 2);
printf("binary: %s\n", buffer);
system("pause");
return 0;
}
fscanf
int fscanf ( FILE * stream, const char * format, ... );
Use
/* fscanf example */
#include <stdio.h>
int main ()
{
char str [80];
float f;
FILE * pFile;
pFile = fopen ("myfile.txt","w+");
fprintf (pFile, "%f %s", 3.1416, "PI");
rewind (pFile);
fscanf (pFile, "%f", &f);
fscanf (pFile, "%s", str);
fclose (pFile);
printf ("I have read: %f and %s \n",f,str);
return 0;
}
fprintf
int fprintf ( FILE * stream, const char * format, ... );
Use
#define _CRT_SECURE_NO_WARNINGS
#include<Windows.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(){
/* fp => file pointer The file pointer If opening the file fails , It will return NULL. If the file does not exist or does not have read and write permissions , Will fail .*/
FILE* fp = fopen("E:/test.txt", "w");
if (fp == NULL) {
printf(" fail to open file ! Error code : %s\n", strerror(errno));//errno A macro definition represents an error
system("pause");
return 0;
}
printf(" File opened successfully ! fp=%p\n", fp);
char buffer[10] = "1111" ;
fprintf(fp,"jiezhe:%s",buffer);
printf(buffer);
system("pause");
return 0;
}
// stdout It's really just a FILE* Variable of type . This is what we call standard output .
// This code is equivalent to printf
fprintf(stdout, "num = %d\n", 10);
// Allied , fscanf(stdin, "xxxxx"); This code is equivalent to scanf
Random, speaking, reading and writing
fseek
Locate the file pointer according to its position and offset

int fseek ( FILE * stream, long int offset, int origin );
#include <stdio.h>
int main ()
{
FILE * pFile;
pFile = fopen ( "example.txt" , "wb" );
fputs ( "This is an apple." , pFile );
fseek ( pFile , 9 , SEEK_SET );
fputs ( " sam" , pFile );
fclose ( pFile );
return 0;
}
ftell
Returns the offset of the file pointer from its starting position
long int ftell ( FILE * stream );
#include <stdio.h>
int main ()
{
FILE * pFile;
long size;
pFile = fopen ("myfile.txt","rb");
if (pFile==NULL) perror ("Error opening file");
else
{
fseek (pFile, 0, SEEK_END); // non-portable
size=ftell (pFile);
fclose (pFile);
printf ("Size of myfile.txt: %ld bytes.\n",size);
}
return 0; }
rewind
Return the file pointer to the beginning of the file
void rewind ( FILE * stream );
#include <stdio.h>
int main ()
{
int n;
FILE * pFile;
char buffer [27];
pFile = fopen ("myfile.txt","w+");
for ( n='A' ; n<='Z' ; n++)
fputc ( n, pFile);
rewind (pFile);
fread (buffer,1,26,pFile);
fclose (pFile);
buffer[26]='\0';
puts (buffer);
return 0; }
Determination of the end of file reading
- Whether the reading of text file is finished , Determine whether the return value is EOF ( fgetc ), perhaps NULL ( fgets )
for example :
fgetc Judge whether it is EOF .
fgets Determine whether the return value is NULL . - Judgment of reading end of binary file , Judge whether the return value is less than the actual number to be read .
for example :
fread Judge whether the return value is less than the actual number to be read .
Refresh cache area
#include <stdio.h>
#include <windows.h>
//VS2013 WIN10 Environmental testing
int main()
{
FILE*pf = fopen("test.txt", "w");
fputs("abcdef", pf);// Put the code in the output buffer first
printf(" sleep 10 second - The data has been written , open test.txt file , Found no content in the file \n");
Sleep(10000);
printf(" Refresh buffer \n");
fflush(pf);// When the buffer is flushed , Write the data in the output buffer to a file ( disk )
// notes :fflush In high version VS It can't be used on
printf(" Sleep again 10 second - here , Open again test.txt file , There's something in the file \n");
Sleep(10000);
fclose(pf);
// notes :fclose When closing a file , It also flushes the buffer
pf = NULL;
return 0; }
Cache refresh time :
1. The buffer is full .
2. fclose Shut down the .
3. fflush The function of this function is to manually refresh the buffer .
Preprocessing
2 The compilation process is the most important

Predefined symbols
__FILE__ // Source files to compile
__LINE__ // The current line number of the file
__DATE__ // The date the file was compiled
__TIME__ // When the file was compiled
__STDC__ // If the compiler follows ANSI C, Its value is 1, Otherwise, it is not defined
define
1. Define constants ~
#define MAX 1000
2. Define an alias for the type ~
#define uint unsigned int
uint num = 10;
3. Customize some " keyword "|
#define and &&
#define also &&
#define If if
#define otherwise else
#define loop for
#define assignment =
#define integer int
int num = 10;
if (num < 10 also num > 0) {
}
integer num assignment 10;
If (num < 10 also num > 0) {
} otherwise {
}
4. Through macros as some " Compile switch ”( Combiner #if This series of exercises f do )
5. Define a code snippet .
#define ADD(x, y) x + y
printf("%d\n", ADD(10, 20));
Macro advantages and problems



3. Macros are not recursive
4. Macro has no parameter check .( Parameter does not write type , It seems to be convenient , But in fact, it's more troublesome . Parameters are not checked , Do you pass the actual parameters correctly , Whether it meets the requirements , I don't know )|
#undef
This instruction is used to remove a macro definition .
Conditional compilation
1.
#if Constant expression
//...
#endif
// Constant expressions are evaluated by the preprocessor .
Such as :
#define __DEBUG__ 1
#if __DEBUG__
//..
#endif
2. Conditional compilation of multiple branches
#if Constant expression
//...
#elif Constant expression
//...
#else
//...
#endif
3. Judge whether it is defined
#if defined(symbol)
#ifdef symbol
#if !defined(symbol)
#ifndef symbol
4. Nested instruction
#if defined(OS_UNIX)
#ifdef OPTION1
unix_version_option1();
#endif
#ifdef OPTION2
unix_version_option2();
#endif
#elif defined(OS_MSDOS)
#ifdef OPTION2
msdos_version_option2();
#endif
#endif
application :
1. Compatible with development and publishing environments ,

2. Compatible with multiple systems ,
3. Prevent header files from repeatedly containing (#pragma once Use... Where defined ),
4. Implement multiline annotations , as follows

5. Support nested

版权声明
本文为[Birds follow February]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220542258941.html
边栏推荐
- 堆的基本操作源代码bing
- ADC
- Markdown 语法支持测试
- STM32 learning note 5 - Calculation of relative position of RGB screen
- qt打包程序打包之跨平台
- The 7th Blue Bridge Cup embedded provincial competition: analog liquid level detection and alarm system "
- Image pyramid, edge detection, image weighted display, histogram equalization
- jeecgboot-online在线开发2
- Universal timer
- qt Debug版本运行正常Release版本运行奔溃
猜你喜欢

QT drawPixmap和drawImage模糊问题

Part 84 leetcode sword refers to offer dynamic programming (I) Fibonacci sequence

The 7th Blue Bridge Cup embedded provincial competition: analog liquid level detection and alarm system "

Error in QT: undefined reference to ` widget:: settime()‘

Geojson file and ShapeFile file single conversion gadget

jeecgboot-online錶單開發-控件配置

I/O多路复用(select/poll/epoll)

Characteristics and usage of QT signal and slot

Write an article about DDT data-driven automated testing

动态内存管理、文件操作、预处理
随机推荐
Code color difference of QT learning
Can data frame, remote frame, error frame, and error reconnection
Invalid transform origin base point setting
Pykmip test
Add a minimize button to the CPropertySheet window
Part 72 leetcode exercise (V) 5 Longest Palindromic Substring
指针所指的地址值及指针所指对象的值(学习笔记)
Part 84 leetcode sword refers to offer dynamic programming (I) Fibonacci sequence
QT add PRI compile run: error: fatal error: no input files problem solving
QQueue使用介绍
ADC
Part 90 leetcode refers to the longest substring of offer dynamic programming (VII) that does not contain duplicate characters
chorme调试工具
机器人工具坐标系标定原理
AD5724 bipolar ADC
Introduction to Intel SGX development
Binary search and its classical applications (left boundary, right boundary, etc.)
Compiling OpenSSL on HP UNIX and using
50道SQL练习题及答案与详细分析
写一个函数的声明,使其返回数组的引用并且该数组包含10个string对象(笔记)