sagomooooooongqi
sagomooooooongqi

Reputation: 3

Gets() and Scanf() Abort Trap 6 Error

I got a problem. I wanted to see the difference between the gets and scanf(). However, my terminal shows up as::

warning: this program uses gets(), which is unsafe. Abort trap: 6

Is there some rule where the gets() and scanfs() can't get together in one code??

#include <stdio.h>

int main(void){
    char passage[10];
    printf("Enter in a passage same one twice:: \n");
    scanf("%s", passage);
    gets(passage);

    printf("Using scanf:: %s", passage);
    printf("Using Gets:: %s", passage);
}

P.S. People say that I am currently writing on the memory that I don't own, but I don't get the problem in this code. Thanks!!!

Upvotes: 0

Views: 428

Answers (3)

Amar Srivastava
Amar Srivastava

Reputation: 373

The basic difference [in reference to your particular scenario],

scanf() ends taking input upon encountering a whitespace, newline or EOF
gets() considers a whitespace as a part of the input string and ends the input upon encountering newline or EOF.


However, to avoid buffer overflow errors and to avoid security risks, its safer to use fgets().

Upvotes: 0

Brandon
Brandon

Reputation: 416

gets() is vulnerable to buffer overflow and is therefore highly discouraged. This vulnerability comes from the fact that there is no way to specify how large the buffer you are passing to gets() actually is. In your case where passage is 10 chars long, imagine if the user typed 10 or more characters. The buffer would then start pointing to un-allocated memory and cause a stack-based buffer overflow.

It would seem the C library your compiler is using is attempting to prevent you from compiling vulnerable code. If you'd still like to use gets() please use fgets() instead and set the file pointer to stdin. The advantage of fgets() is it allows you to specify the buffer size. See more about fgets() here.

Update: also please take note of MikeCAT's comment to this post referencing the dangers of scanf("%s") as you've used it.

Upvotes: 2

qDot
qDot

Reputation: 430

It's not using gets and scanf together, it's using gets at ALL. The manpage for gets (http://man7.org/linux/man-pages/man3/gets.3.html) says it better than I could:

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead. For more information, see CWE-242 (aka "Use of Inherently Dangerous Function") at http://cwe.mitre.org/data/definitions/242.html

Upvotes: 1

Related Questions