C++ - why does this cause a segfault?

Discussion in 'Computer Programming, Emulation, and Game Modding' started by Nyap, Jul 18, 2016.

  1. Nyap
    OP

    Nyap HTML Noob

    Banned
    973
    344
    Jan 13, 2016
    That Chaos Site
    Here's the code:
    main.cpp
    compiler.cpp
    declerations.h
    buffer.h
    There's a segmentation fault in the extractToken(buffer&) member function (buffer.h) and for the love of god I can't figure out why
    Plz help
     
  2. mbcrazed

    mbcrazed GBAtemp Advanced Fan

    Member
    647
    230
    Nov 10, 2012
    China
    GBATemp
    Hm... Well, I really don't know if I'm right because I stopped programming a while ago, but giving a quick look at your code there could be an out of bounds access of one of your arrays. I'm not too sure though! You're going to have to ask someone who knows much more than me! Sorry I can't help that much! :/
     
  3. Nyap
    OP

    Nyap HTML Noob

    Banned
    973
    344
    Jan 13, 2016
    That Chaos Site
    meh I think I've found the problem anyway
    I'm not sure how to fix it in a not-workaroundy manner though
     
  4. Dr_Doom

    Dr_Doom Advanced Member

    Newcomer
    95
    28
    Mar 10, 2016
    What did you think was the problem
     
  5. PewnyPL

    PewnyPL GBAtemp Advanced Fan

    Member
    586
    250
    Feb 2, 2014
    Poland
    I think the issue is the very first line in main. If you launch the exe without ANY arguments, then argv is void, therefore, accessing/writing to an uninitialised array will cause a segfault. If you want to do such a workaround as you did here, try to use new to initialise a 2 element argv and then assign "lol.txt" to it's second element.
     
  6. sandytf

    sandytf GBAtemp Regular

    Member
    122
    50
    May 5, 2013
    United States
    Your problem is related to the first line in the main function. The two parameters argc and argv should be treated as read only values. You should never edit them. The fix for your program is rather simple. Create a new variable, probably a std::string, and set that to the desired file name. If you want the user to optionally set a filename from the commandline, then use a simple if statement. If argc equals 1, set the string to the value in argv [1], otherwise set it to your default value.
     
  7. Nyap
    OP

    Nyap HTML Noob

    Banned
    973
    344
    Jan 13, 2016
    That Chaos Site
    I edited one of the arguments for debugging purposes
    That's not the problem, the problem is within the extractToken member function from the buffer class. The function would attempt to copy a string to the "Buffer" pointer, instead I should have made a dynamically allocated array, copy the string there and set the pointer to that

    The program checks to make sure the user input a filename