Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overflow in C function strcpy() [duplicate]

Tags:

c

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.

like image 709
LittleBill Avatar asked Dec 19 '22 12:12

LittleBill


1 Answers

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;
}
like image 200
Elias Van Ootegem Avatar answered Dec 29 '22 00:12

Elias Van Ootegem