Search code examples
csegmentation-faulttokenize

Segmentation fault when using strcat()


I'm getting a segmentation fault when I call strcat(); however, I've already malloc'd the destination string and initialized the previous string. This is in an assignment to make a shell in C, I'm just getting tripped up on this error. Here's what the code looks like for this particular segment. To note, this is a part of a larger program so I only included the bits I thought were relevant.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>

int main(int argc, char* argv[])
{
    char* token, *file_name, *srt_cmm, *str_chr1;
    str_chr1 = "<";
    file_name = (char*)malloc(100);
    srt_cmm = (char*)malloc(500);
    srt_cmm = "sort ";
    


    if(strstr(token, str_chr1) != NULL)
    {
        token = strtok(NULL, " ");
        file_name = token;
        strcat(srt_cmm, file_name);
        execvp("sort", &srt_cmm);
    }

    free(file_name);
    free(srt_cmm);
}

The first thing I did was allocate both of the variables more space in an attempt to see if that'd fix it. Other than that I just put printf statements in to see where it was getting hung up, it clears the file_name assignment but throws the error at the strcat(). I've checked, and file_name is being populated by the tokenized string.


Solution

  • Compiling your code with gcc -Wall t.c produces:

    t.c: In function ‘main’:
    t.c:17:8: warning: ‘token’ is used uninitialized [-Wuninitialized]
       17 |     if(strstr(token, str_chr1) != NULL)
          |        ^~~~~~~~~~~~~~~~~~~~~~~
    t.c:9:11: note: ‘token’ was declared here
        9 |     char* token, *file_name, *srt_cmm, *str_chr1;
          |           ^~~~~
    

    which is the first (of many) problems with your code.

    The second obvious problem is that strtok(NULL, " "); without a previous call to strtok with non-NULL argument makes no sense.

    There are more problems (such as a memory leak when re-assigning srt_cmm).