Memahami Pengurusan Memori, Penunjuk dan Penunjuk Fungsi dalam C

王林
Lepaskan: 2024-07-17 00:10:11
asal
1072 orang telah melayarinya

Understanding Memory Management, Pointers, and Function Pointers in C

Dalam pengaturcaraan C, pengurusan memori yang cekap dan penggunaan penunjuk adalah penting untuk mencipta aplikasi yang mantap dan berprestasi tinggi. Panduan ini menyediakan gambaran keseluruhan yang komprehensif tentang pelbagai jenis memori, penunjuk, rujukan, peruntukan memori dinamik dan penunjuk fungsi, lengkap dengan contoh untuk membantu anda menguasai konsep ini. Sama ada anda baru menggunakan C atau ingin mendalami pemahaman anda, panduan ini merangkumi topik penting untuk meningkatkan kemahiran pengekodan anda.

Jenis ingatan yang berbeza.

Terdapat 5 jenis memori berbeza yang akan anda hadapi semasa pengaturcaraan dalam C.

1. Segmen teks

Kod terkumpul anda disimpan di sini. Arahan kod mesin untuk program anda. Segmen teks dibaca sahaja supaya anda tidak boleh menukar sebarang data tetapi anda boleh mengaksesnya. Lebih jauh ke bawah kita akan bercakap tentang penunjuk fungsi. Penunjuk tersebut menunjukkan fungsi dalam segmen ini.

2. Segmen Data Dimulakan

Pembolehubah global dan statik disimpan di sini, dengan nilai khusus sebelum program dijalankan dan kekal boleh diakses sepanjang program.

Perbezaan antara pembolehubah statik dan global ialah skop, pembolehubah statik boleh diakses dalam fungsi atau blok, ia ditakrifkan tetapi pembolehubah global boleh diakses dari mana-mana sahaja dalam program anda.

Pembolehubah biasa dialih keluar selepas fungsi selesai dilaksanakan manakala pembolehubah statik kekal.

3. Segmen Data Bersatu (BSS)

Pada asasnya sama seperti segmen data yang dimulakan tetapi terdiri daripada pembolehubah tanpa nilai khusus yang diberikan kepadanya. Mereka mempunyai nilai 0 secara lalai.

4. Timbunan

Di sini anda mempunyai ingatan dinamik yang anda sebagai pengaturcara boleh menguruskan pada masa jalankan. Anda boleh memperuntukkan memori dan memori percuma dengan fungsi seperti malloc, calloc, realloc dan percuma.

5. Tumpukan

Anda mungkin agak biasa dengan timbunan. Memori tindanan menguruskan pelaksanaan fungsi dengan menyimpan pembolehubah tempatan, argumen dan nilai pulangan. Memori dalam timbunan dikeluarkan selepas fungsi selesai dilaksanakan.

Jenis data dan jumlah storan.

Dalam C anda mempunyai jenis data yang berbeza dan yang paling biasa ialah int, float, double dan char. Saya tidak akan bercakap banyak tentang jenis data tetapi yang penting ialah mengetahui berapa banyak bait jenis data tertentu ada dalam ingatan. Berikut adalah senarai, ingatlah.

Int: 4 bait,
Terapung: 4 bait,
Ganda: 8 bait,
Char: 1 bait.

Anda boleh menyemak saiz jenis data dengan kaedah sizeof().

Petunjuk dan Rujukan.

Apabila anda menetapkan pembolehubah seperti;

int number = 5; 
Salin selepas log masuk

Sistem akan menyimpan nilai 5 dalam ingatan. Tetapi di mana dalam ingatan?

Dalam ingatan sebenarnya terdapat alamat, dan itulah cara anda boleh menjejaki nilai yang telah anda simpan.

Rujukan ialah alamat pembolehubah. Cukup keren, bukan?

Untuk mengakses rujukan penggunaan pembolehubah & diikuti dengan nama pembolehubah.

Untuk mencetak rujukan kepada konsol, kami menggunakan penentu format p.

int number = 5;

printf(“%d”, number);
// prints out 5 

printf(“%p”, &number);
// prints out the ref: 0x7ffd8379a74c
Salin selepas log masuk

Anda mungkin mendapat alamat lain yang dicetak.

Sekarang untuk menjejaki rujukan itu gunakan penuding untuk menyimpan rujukan.

Buat pembolehubah penunjuk dengan menggunakan *.

int number; 

int* pointer = &number;

printf(“%p”, pointer);
// 0x7ffd8379a74c
Salin selepas log masuk

Untuk mendapatkan nilai daripada penunjuk, anda boleh menggunakan dereference. Untuk merujuk nilai yang anda gunakan * sebelum penunjuk. Jadi * digunakan kedua-duanya untuk mencipta penunjuk dan membatalkan rujukannya, tetapi dalam konteks yang berbeza.

int number = 5; // create variable.

int* pointer = &number //store the reference in the pointer

printf(“%p”, pointer); // print the reference
// 0x7ffd8379a74c

printf(“%d”, *pointer); // dereference the value. 
// 5
Salin selepas log masuk

Ini hebat kerana dengan penunjuk anda boleh menghantar nilai melalui rujukan dan bukan menyalin nilai. Ini adalah cekap memori dan berprestasi.

Apabila anda menghantar nilai kepada fungsi sebagai argumen dalam bahasa peringkat tinggi, anda menyalin nilai tetapi dalam C anda boleh menghantar rujukan dan memanipulasi nilai secara terus dalam ingatan.

#include <stdio.h>

void flipValues(int *a, int *b) { // receives two pointers of type int
  int temp = *a; // dereference pointer a and store it’s value in temp
  *a = *b; // dereference pointer b and store in pointer a
  *b = temp; // dereference b and change value to the value of temp
}

int main(void) {
  int a = 20;
  int b = 10;
  flipValues(&a, &b); // pass the references of a and b
  printf("a is now %d and b is %d", a, b);
  // a is now 10 and b is 20
  return 0;
}
Salin selepas log masuk

Penunjuk boleh diisytiharkan sebagai nama int*; atau int *nama; kedua-dua gaya adalah betul dan boleh ditukar ganti.

Agihkan dan Agihkan memori dinamik.

Apabila anda mengisytiharkan pembolehubah seperti int num = 5; di dalam fungsi termasuk fungsi utama, pembolehubah itu disimpan dalam tindanan dan apabila fungsi selesai melaksanakan pembolehubah itu dialih keluar.

Tetapi kini kami akan memperuntukkan memori secara dinamik dalam timbunan. Kemudian kita mempunyai kawalan penuh ke atas berapa banyak memori yang kita perlukan, dan ia akan berterusan sehingga kita mengagihkannya.

Malloc dan Calloc.

Kita boleh menggunakan fungsi malloc atau calloc untuk memperuntukkan memori.

Malloc mengambil satu parameter yang mewakili saiz memori untuk diperuntukkan dalam bait.

Calloc mengambil dua parameter, jumlah item dan jumlah memori dalam bait yang diduduki setiap item.

mallok(saiz)
calloc(jumlah, saiz)

calloc initializes all allocated memory to 0, while malloc leaves the memory uninitialized, making malloc slightly more efficient.

You can use sizeof to indicate how much memory you need. In the example we use malloc to allocate space for 4 integers.

int* data; 
data = malloc(sizeof(int) * 4);
Salin selepas log masuk

Here is a visualization:

Pointer->[],[],[],[] [],[],[],[] [],[],[],[] [],[],[],[]

  1. Each bracket is a byte so here we see 16 bytes in memory.
  2. The malloc function allocates 4 x 4 bytes in memory, resulting in 16 bytes.
  3. int* data is a pointer of type int, so it points to the 4 first bytes in memory.

Therefore, pointer + 1 moves the pointer one step to the right, referring to the next integer in memory, which is 4 bytes away.

int* data; 
  data = malloc(sizeof(int) * 4);

  *data = 10; // change first value to 10.
  *(data + 1) = 20; // change second value to 20.
  *(data + 2) = 30;
  *(data + 3) = 40;

  for(int i = 0; i < 4; i++) {
      printf("%d\n", *(data + i));
  }
Salin selepas log masuk

This is how an array work!

When you declare an array, the array name is a pointer to its first element.

int numbers[] = { 10, 20, 30, 40 };
  printf("%p\n", &numbers); 
  printf("%p", &numbers[0]);
  // 0x7ffe91c73c80
  // 0x7ffe91c73c80
Salin selepas log masuk

As shown, the address of the array name is the same as the address of its first element.

Realloc

Sometimes you want to reallocate memory. A normal use case is when you need more memory then you initially allocated with malloc or calloc.

The realloc function takes 2 parameters. A pointer to where your data currently is located, and the size of memory you need.

int* pointer2 = realloc(*pointer1, size);
Salin selepas log masuk

The realloc function will first check if the size of data can be stored at the current address and otherwise it will find another address to store it.

It’s unlikely but if there is not enough memory to reallocate the function will return null.

int *ptr1, *ptr2;

// Allocate memory
ptr1 = malloc(4);

// Attempt to resize the memory
ptr2 = realloc(ptr1, 8);

// Check whether realloc is able to resize the memory or not
if (ptr2 == NULL) {
  // If reallocation fails
  printf("Failed. Unable to resize memory");
} else {
  // If reallocation is sucessful
  printf("Success. 8 bytes reallocated at address %p \n", ptr2);
  ptr1 = ptr2;  // Update ptr1 to point to the newly allocated memory
}
Salin selepas log masuk

Free memory

After you have allocated memory and don’t use it anymore. Deallocate it with the free() function with a pointer to the data to be freed.

After that, it is considered good practice to set the pointer to null so that the address is no longer referenced so that you don’t accidentally use that pointer again.

int *ptr;
ptr = malloc(sizeof(*ptr));

free(ptr);
ptr = NULL;
Salin selepas log masuk

Remember that the same memory is used in your whole program and other programs running on the computer.

If you don’t free the memory it’s called data leak and you occupy memory for nothing. And if you accidentally change a pointer you have freed you can delete data from another part of your program or another program.

Create a Vector (dynamic array).

You can use your current knowledge to create a dynamic array.

As you may know, you can use structs to group data and are powerful to create data structures.

#include <stdio.h>
#include <stdlib.h>

struct List {
  int *data; // Pointer to the list data
  int elements; // Number  of elements in the list 
  int capacity; // How much memmory the list can hold
};

void append(struct List *myList, int item);
void print(struct List *myList);
void free_list(struct List *myList);

int main() {
    struct List list;
    // initialize the list with no elements and capazity of 5 elements
    list.elements = 0;
    list.capacity = 5;
    list.data = malloc(list.capacity * sizeof(int));
    // Error handeling for allocation data
    if (list.data == NULL) {
    printf("Memory allocation failed");
    return 1; // Exit the program with an error code
    }
    // append 10 elements
    for(int i = 0; i < 10; i++) {
      append(&list, i + 1);
    };
    // Print the list 
    print(&list);
    // Free the list data
    free_list(&list);

    return 0;
}

// This function adds an item to a list
void append(struct List *list, int item) {
    // If the list is full then resize the list with thedouble amount
    if (list->elements == list->capacity) {
    list->capacity *= 2;
    list->data = realloc( list->data, list->capacity * sizeof(int) );
    }
    // Add the item to the end of the list
    list->data[list->elements] = item;
    list->elements++;
}

void print(struct List *list) {
    for (int i = 0; i < list->elements; i++) {
    printf("%d ", list->data[i]);
    } 
}

void free_list(struct List *list) {
    free(list->data);
    list->data = NULL;
}
Salin selepas log masuk

Static data

Global variables.

When declaring a variable above the main function they are stored in the data segment and are allocated in memory before the program starts and persists throughout the program and is accessible from all functions and blocks.

#include <stdio.h>
int globalVar = 10; // Stored in initilized data segment
int unitilizedGlobalVar; // Stored in uninitialized data segment

int main() {
    printf("global variable %d\n", globalVar);            printf("global uninitilized variable %d", unitilizedGlobalVar);
    // global variable 10
    // global uninitilized variable 0
    return 0;
}
Salin selepas log masuk

Static variables

They work the same as global ones but are defined in a certain block but they are also allocated before the program starts and persist throughout the program. This is a good way of keeping the state of a variable. Use the keyword static when declaring the variable.

Here is a silly example where you have a function keeping the state of how many fruits you find in a garden using a static variable.

#include <stdio.h>

void countingFruits(int n) {
    // the variable is static and will remain through function calls and you can store the state of the variable
    static int totalFruits;
    totalFruits += n;
    printf( "Total fruits: %d\n", totalFruits);
}

void pickingApples(int garden[], int size) {
    // search for apples
    int totalApples = 0;
    for(int i = 0; i < size; i++) {
        if(garden[i] == 1) {
            totalApples++;
        }
    }
    countingFruits(totalApples);
}

void pickingOranges(int garden[], int size) {
    // search for oranges
    int totalOranges = 0;
    for(int i = 0; i < size; i++) {
        if(garden[i] == 2) {
            totalOranges++;
        }
    }
    countingFruits(totalOranges);
}

int main() {
    // A garden where you pick fruits, 0 is no fruit and 1 is apple and 2 is orange
    int garden[] = {0, 0, 1, 0, 1, 2,
                    2, 0, 1, 1, 0, 0,
                    2, 0, 2, 0, 0, 1
                    };
    // the length of the  garden
    int size = sizeof(garden) / sizeof(garden[0]);
    pickingApples(garden, size); 
    // now the total fruits is 5
    pickingOranges(garden, size);
    // now the total fruits is 9
    return 0;
}
Salin selepas log masuk

Understanding Function Pointers in C.

Function pointers are a powerful feature in C that allow you to store the address of a function and call that function through the pointer. They are particularly useful for implementing callback functions and passing functions as arguments to other functions.

Function pointers reference functions in the text segment of memory. The text segment is where the compiled machine code of your program is stored.

Defining a Function Pointer

You define a function pointer by specifying the return type, followed by an asterisk * and the name of the pointer in parentheses, and finally the parameter types. This declaration specifies the signature of the function the pointer can point to.

int(*funcPointer)(int, int)
Salin selepas log masuk

Using a Function Pointer

To use a function pointer, you assign it the address of a function with a matching signature and then call the function through the pointer.

You can call a function of the same signature from the function pointer

#include <stdio.h>

void greet() {
    printf("Hello!\n");
}

int main() {
    // Declare a function pointer and initialize it to point to the 'greet' function
    void (*funcPtr)();
    funcPtr = greet;

    // Call the function using the function pointer
    funcPtr();

    return 0;
}
Salin selepas log masuk

Passing Function Pointers as Parameters

Function pointers can be passed as parameters to other functions, allowing for flexible and reusable code. This is commonly used for callbacks.

#include <stdio.h>

// Callback 1
void add(int a, int b) {
    int sum  = a + b;
    printf("%d + %d = %d\n", a, b, sum);
}

// Callback 2
void multiply(int a, int b) {
    int sum  = a * b;
    printf("%d x %d = %d\n", a, b, sum);
}

// Math function recieving a callback
void math(int a, int b, void (*callback)(int, int)) {
    // Call the callback function
    callback(a, b);
}

int main() {
    int a = 2;
    int b = 3;

    // Call math with add callback
    math(a, b, add);

    // Call math with multiply callback
    math(a, b, multiply);

    return 0;
}
Salin selepas log masuk

Explanation of the Callback Example

Callback Functions: Define two functions, add and multiply, that will be used as callbacks. Each function takes two integers as parameters and prints the result of their respective operations.

Math Function: Define a function math that takes two integers and a function pointer (callback) as parameters. This function calls the callback function with the provided integers.

Main Function: In the main function, call math with different callback functions (add and multiply) to demonstrate how different operations can be performed using the same math function.

The output of the program is:

2 + 3 = 5
2 x 3 = 6
Salin selepas log masuk

Thanks for reading and happy coding!

Atas ialah kandungan terperinci Memahami Pengurusan Memori, Penunjuk dan Penunjuk Fungsi dalam C. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!