简体   繁体   中英

C - segfault when using strcmp()

I am getting a segfault when using strcmp(). I have tried debugging using gdb and when I run it (without arguments) I get a segfault. When I backtrace, it indicates the segfault is at line 20, but I can't figure out why it's segfaulting. The strcmp() statement is on line 20. I will include lines 0-21 in my post, but can add more if necessary.

The segfault statements when I use the run command are as follows:

Program received signal SIGSEGV, Segmentation fault.
__strcmp_sse2 () at ../sysdeps/x86_64/multiarch/../stcmp.S:213
213 ../sysdeps/x86_64/multiarch/../strcmp.S: No such file or directory.

So then I do a backtrace and get this:

#0 __strcmp_sse2 () at ../sysdeps/x86_64/multiarch/../strcmp.S:213
#1 0x0000000000400aa6 in main (c=1, v=0x7fffffffead8) at myls.c:20

Here is my code from lines 0-21:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>
#include <fcntl.h>
#include <pwd.h>
#include <string.h>
#include <grp.h>

int main(int c, char *v[])
{
    DIR *directory = NULL;
    strut direct *dir_pointer = NULL;
    int i = 0;
    char cwd[1024];

    if(strcmp(v[1], "-i") == 0){ //line 20, where the segfault happens
        ...

any tips/help appreciated.

You are calling without arguments (c = 1) and accessing the first argument given to the program (as if c was 2)..

I suggest you to read this answer

What does int argc, char *argv[] mean?

You're either not passing arguments to the program, or it segfaults directly after the if statement. The strcmp works.

Edit: Just realized you're NOT passing it without arguments. You're referencing v[1] when there is no v[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM