Buffer Overflow

Asked

Viewed 89 times

-1

Good afternoon, folks, I’d like to request a hand on the college ATV;

About this code used as an example:

#include <stdio.h>
#include <string.h>

int main()

{
char str0[6]="98765",str1[5]="abcd",str2[10]="efghijklm";

printf("str0 = %s\t str1 = %s\t str2 = %s\n",str0,str1,str2);
strcpy(str1,"1234567");
printf("str0 = %s\t str2 = %s\n",str0,str2);
}

the following questions were asked:

first) What happens with the string "str0"?

2nd) What would be your suggestion to avoid the problem?

From what I understand on the subject, the first question on the str0 would only suffer from buffer overflow if there were more characters than 6, that’s not it?

and on question 2), the use of the fgets() command would be useful to avoid buffer overflow?

I would really appreciate it if someone could help, I’m two days hammering on this issue :@

1 answer

0

Well, I’m starting from the concept that you understand what a buffer overflow is.

On the first question: When you use the function strcpy() you copy all content from one variable to another, however if what you are copying is larger than the reserved size for the destination variable, other memory addresses (that do not belong to the destination variable) will be overwritten, causing or allowing anomalous behavior.

Example:

char str1[] = "abc";
char str2[2];

strcpy(str2, str1); // vai sobreescrever endereços na memória, pois "abc" precisa de 3 posições, e str2 só tem duas

A solution that is not yet safe is to use the strncpy() which is a version in which it must be specified how much memory space is available at the destination, in addition to performing automatic padding when space is left. However even this one has problems related to not guaranteeing that the final character in the destination will be "null terminated"

Example:

char str1[] = "abc";
char str2[2];
    
strncpy(str2, str1, sizeof(str2)); // Vai copiar somente "ab", "sem overflow"

On the second question: To avoid overflow the ideal is to use strlcpy() or snprintf() that are safe against this.

Obs: As commented below, has the ending character ' 0', I omitted for "aesthetic" reason, but know that exists.

References:

Strlcpy

Snprintf

  • Just one detail: you forgot the string terminator character, '0', which occupies a position. So "abc" occupies 4 positions and not 3.

  • If I understand correctly, is str0 being overwritten in str1 because of the use of strncpy()? Thank you so much for your help, your explanation helped me a lot!

  • Maybe so, and in case you meant strcpy()?

  • Yes, I meant strcpy! Thanks for the help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.