"..."
). In C, they are treated as arrays of characters with a null character (\0
) at the end to indicate the string's end.scanf()
.char myString[] = "Hello, World!";
char anotherString[256]; // Allocate space for 256 characters (including null terminator)
scanf("%s", anotherString); // Read a string from user input
0
.char myString[] = "Hello, World!";
printf("The first character is: %c\n", myString[0]); // Outputs: H
char str1[] = "Apple";
char str2[] = "Orange";
if(strcmp(str1, str2) == 0){
printf("These strings are equal.\n");
} else {
printf("These strings are not equal.\n");
}
What causes it:
char myString[1]; // Allocate space for only one character plus null terminator
scanf("%s", myString); // Read a string from user input, causing buffer overflow
Error message:
Program received signal SIGSEGV: Segmentation fault: memory accessed outside of its intended address.
Solution:
Allocate enough space for the expected length of the string plus one character for the null terminator.
Why it happens: Buffer overflow occurs when you try to store more data in a buffer than it can hold, leading to unpredictable behavior and potential security vulnerabilities.
How to prevent it: Always allocate sufficient space for your strings and be mindful of input size when using functions like scanf()
.
What causes it:
char str1[] = "Apple";
char str2[] = "apple"; // Case-sensitive comparison in C
if(strcmp(str1, str2) == 0){
printf("These strings are equal.\n"); // Does not output this message
}
Solution: Use strcasecmp()
instead of strcmp()
for case-insensitive comparisons.
Why it happens: In C, string comparison is case-sensitive, meaning that upper and lowercase letters are treated as distinct characters.
How to prevent it: Use the strcasecmp()
function for case-insensitive comparisons.
strlen()
to determine the length of a string before attempting to access its contents.scanf()
.<string.h>
and <ctype.h>
for additional string manipulation functionality."..."
).strcmp()
or strcasecmp()
.<string.h>
and <ctype.h>
for additional string manipulation functionality.