C - Segmentation Fault with strcmp?

前端 未结 5 932
甜味超标
甜味超标 2020-11-27 08:35

I appear to be getting a segmentation fault somewhere with the strcmp function. I\'m still very new to C and I can\'t see why it gives me the error.

int line         


        
5条回答
  •  渐次进展
    2020-11-27 09:17

    If you are on linux, try valgrind. It can tell you about invalid accesses, memory leaks, uninitialized variables, etc. The output may seem messy and hard to read, but if you keep trying, it will reward you. What is going on:

    1. build you program with -g switch to include debugging information
    2. run the program using valgrind: valgrind ./myprogram
    3. profit by reading output

    As I said, the output may seem very messy, so maybe first try some simple program (plain empty main) to see how it looks like when everything is ok, then try to deliberately crash your program, like:

    int *bullet = 0;
    *bullet = 123;
    

    and see the output.


    A nice basic introduction with examples can be found here.


    As you provided valgrind output, I would start to fix problems listed there. First the Conditional jump or move depends on uninitialised value(s) error. You can rerun valgrind with --track-origins=yes as valgrind suggests to see more details, then fix it (you don't have line numbers in the code snippets, I cannot help you more).

    ./valgrind --track-origins=yes ./myprogram      #don't switch parameters!
    

    Then the Invalid read of size 1 error means you are already accessing memory which is not yours, but reading it only, so it "doesn't mind". But it is still an error which should not happen, so fix it (if not fixed by the first error fix).

    And finally, the Access not within mapped region is a write to memory which is not allocated.

    Now try fixing the errors (in order valgrind lists them) following valgrind suggestions (like reruning it with switches).

提交回复
热议问题