0

I am new to programming trying to understand concepts of asking information by the console. When I execute this program I get a SEGV error, but I can't find what I am doing wrong. As far as I know, this happens when I try to modify a string literal, but there must be something else. Here is my code:

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

#define BUFFSIZE 255 

int main()
{
    char *action;
    char buffer[BUFFSIZE], *aux1, *aux2;
    bool end = false;

    while (!end) 
    {
        size_t ct;

        fgets(buffer, BUFFSIZE, stdin);
        sscanf(buffer,"%s%s%s", action, aux1, aux2);

        if (strcmp(action, "finish") == 0)
        {
            end = true;
        } 
        else if (strcmp(action, "option2") == 0)
        {
            printf("%s", action);
        }
        else if (strcmp(action, "option3") == 0)
        {
           printf("%s", action);
        }  
    }
}
mkareshky
  • 202
  • 3
  • 7
  • 6
    `action, aux1, aux2` are uninitialized pointers. But you do `sscanf` as if they're pointing somewhere valid. – P.P Aug 24 '20 at 09:15
  • 2
    sscanf doesn't reserve memory for your, this is up to you. – hetepeperfan Aug 24 '20 at 09:16
  • 1
    For a reasonably recent GCC or Clang, use `-fsanitize=address` while compiling. This helps you to catch the cause of a segfault before it happens (at the cost of some performance). – Thomas Aug 24 '20 at 09:16
  • 1
    In the future you can debug this yourself by running the code under gdb or a similar debugger, and when you get the SIGSEGV you can get it to show you a backtrace to where the error happened. – Rup Aug 24 '20 at 09:17
  • 1
    @KKKKK That wouldn't cause a runtime error though, and since OP said this was a SEGV not an Access Violation this probably isn't Windows and Visual C++. – Rup Aug 24 '20 at 09:18

0 Answers0