Copying Strings
Glissez pour afficher le menu
Copying strings in C is a fundamental operation, but it must be performed with care to avoid common pitfalls such as buffer overflows and data corruption. The standard library provides functions like strcpy and strncpy for copying strings from one character array to another. Understanding how these functions work, and their limitations, is crucial for writing safe and efficient C code.
copy_str.c
1234567891011121314#include <stdio.h> #include <string.h> int main() { char source[] = "Hello, world!"; char destination[20]; // Copy source into destination using strcpy strcpy(destination, source); printf("Destination: %s\n", destination); return 0; }
In this example, you see how strcpy copies the contents of the source string into the destination buffer. It is essential to ensure that the destination array is large enough to hold the entire source string, including the null-terminator. If the destination is too small, strcpy will write past the end of the buffer, causing undefined behavior and potentially leading to security vulnerabilities or program crashes.
safe_copy_str.c
12345678910111213141516#include <stdio.h> #include <string.h> int main() { char source[] = "Hello, C!"; char destination[10]; // Safely copy up to 9 characters, leaving space for null-terminator strncpy(destination, source, sizeof(destination) - 1); // Explicitly null-terminate, as strncpy does not always do so destination[sizeof(destination) - 1] = '\0'; printf("Safely copied: %s\n", destination); return 0; }
Using strncpy allows you to specify the maximum number of characters to copy, helping to prevent buffer overflows by ensuring you never write more data than the destination can hold. Unlike strcpy, strncpy will not write past the specified limit, but it does not always add a null-terminator if the source is longer than the destination. That is why it is good practice to manually set the last byte of the destination to '\0' after copying. This approach makes strncpy a safer choice than strcpy when working with buffers of limited size.
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion