1

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.

donut juice
  • 257
  • 6
  • 19
  • 3
    "when I run it (without arguments) " - Huh??? you had *better* provide at least one argument, or per the standard `v[1]` is NULL; `strcmp` doesn't play well with `NULL`, for *either* of its arguments. – WhozCraig Apr 03 '16 at 21:38
  • @WhozCraig some background on this: I am writing my own ls program that mimics the unix `ls` command. When I run it with `./myls`, that is c=1 correct? And when I run it with `./myls -l` that is c = 2? and the `-l` = v[1]? – donut juice Apr 03 '16 at 21:48
  • I strongly advise you carefully [read the q&a at the link](http://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean) provided by Kons below. It answers that question, and much, *much* more. – WhozCraig Apr 03 '16 at 21:52

2 Answers2

2

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?

Community
  • 1
  • 1
Kons
  • 94
  • 7
  • 1
    What does this have to do with the "strcmp.S" not begin found? As the error is "No such file or directory." – jaques-sam Jan 22 '18 at 14:00
0

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]

One Normal Night
  • 332
  • 1
  • 2
  • 12