-1

i'm trying to get and print a string with gets and puts but i get a segmentation fault error when i use them togheter. this is the code i'm trying to get this working. [i type the string "prova" to test it]

int main()
{
    char *s;
    gets(s);
    puts(s);
    return 0;
}

if i change "gets" with "scanf" i get the same error. if i change "puts" with "printf("%s", s)" i get the output. if i declare char *s = "prova" and then puts(s) i get the output.

i also tried to change char *s; with char s[] but i get the same error.

where i'm i wrong on this? ty very much

i know gets is bad, is just bc i'm writing exercise from "C how to program, fifth edition" by Deitel and Deitel

user3757339
  • 7
  • 1
  • 4

3 Answers3

3

You have multiple problems with that piece of code. To start with gets have been deprecated since the C99 standard, and in the C11 standard it has been removed. The reason is that it's not very safe, and has no bounds-checking and so can write beyond the bounds of the memory you pass to it leading to buffer overflows.

Secondly, you use the uninitialized local variable s. The value of an uninitialized variable is indeterminate, and will be seemingly random. Using an uninitialized local variable leads to undefined behavior, which often leads to crashes.

Another problem is if you initialize s to point to a literal strings. Literals strings are constant (read-only) arrays of characters, and attempting to write to it will again lead to undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

You need to allocate some room for the string:

char s[256];
gets(s);
puts(s);

But gets is bad. (It doesn't know how big your buffer is, so what happens if more than 255 characters are read?)

Community
  • 1
  • 1
James M
  • 18,506
  • 3
  • 48
  • 56
0

The most important mistake you have is that you are declaring a char pointer, but you are not reserving the space in memory where the characters will be stored, so you got a pointer that point to some random memory adress that you should'nt use. the "right" thing to do will be:

#include <stdio.h>
#include <stdlib.h>

#define LENGHT 20
int main()
{
    char *s;
    s=malloc(sizeof(char)*LENGHT);  //here you make the pointer point to a memory adress that you can use
    gets(s);
    puts(s);
    free (s);
    return 0;
}

But also is strongly recommend to avoid using gets because that function doesn't check for the length of the input, so use fgets instead that allow you to do that, you will only need to set the data stream to stdin. The code will be:

#include <stdio.h>
#include <stdlib.h>

#define LENGHT 20
int main()
{
    char *s;
    s=malloc(sizeof(char)*LENGHT);
    fgets(s,20,stdin);
    puts(s);
    free(s);
    return 0;
}
sir psycho sexy
  • 780
  • 7
  • 19