I'm programming in C language in Linux envirioment and I'm a confused aboute why segmentation fault does not occur in this code:
int main(){
char buffer[4];
char tmp="qqqqqqqqqqqqqqqqqqqqqqqq";
char *r;
r=strcpy(buffer,tmp);
return 0;}
I use variable tmp more longer than buffer and despite it i can stamp buffer variable right without any error.
Furthermore I don't undestrand why in this case:
int main(){
static char buffer[4];
int i=0;
while(i<5){
(*(buffer+i)='a');
i++;}
return 0;}
the segmentation fault occur only if I does not declare buffer static.
Thank you in advance.
In the first case, buffer
is large enough to hold 4 chars, generally that means it can hold 3 characeters + 1 nul-char. strcpy
does not allow you to protect against overflows, whereas strncpy
does. It's a simple matter of writing:
const char *tmp = "your string"; // const char *, not char
char buffer[4];
strncpy(buffer, tmp, (sizeof buffer) - 1); // sizeof char array == number of characters buffer can store
buffer[3] = '\0';//add terminating nul char
In the second case, the biggest issue is that your while
loop is accessing an index that is out of bounds (i<5
means the last iteration will have i == 4). Arrays are zero-indexed, so the last valid index for buffer
is 3. Change the loop to:
while(i<3) {
buffer[i++] = 'a';
}
buffer[i] = '\0';
You can do away with the nul char by initializing buffer
correctly:
char buffer[4] = "";
So I'd probably write something like this:
int main ( void )
{
const char *tmp = "some long string";
char buffer[4] = "";
strncpy(buffer, tmp, (sizeof buffer) - 1);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With