Search code examples
csegmentation-faulttolower

Segmentation fault Ubuntu C


I am getting a segmentation fault when I want to run this program. It is supposed to by a self-written grep function but case-insensitive. The same code for case-sensitive works just fine so it might have something to do with tolower()?. Please help. Used VS code in Ubuntu on a Windows PC.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>


int main (int argc, char *argv[]) {
    if (argc > 3) {
        printf("Too many arguments. Only use 2: your search string and the file name.");
        return -1;
    }

    //FILE * fp;
    FILE * fp = fopen(argv[2], "r");
    if(fp == NULL) {
           perror("Unable to open file!");
           return -1;
       }
    char * buffer = NULL;
    size_t bufsize = 0;
    char * lowerBuffer = malloc(sizeof(strlen(buffer)));

    for (int i = 0; buffer[i] != '\0'; i++) {
        lowerBuffer[i] = tolower(buffer[i]);
    }
    
    printf("tolower: %s", lowerBuffer);

    while (getline(&buffer, &bufsize, fp) != -1) {
        if (strstr(buffer, argv[1]))
        {
            printf("%s", buffer);
        }
                
        //printf("%zd", strlen(buffer));
    }
    
    fclose(fp);
    free(buffer);

    //getline();

    return 0;
}

Compiled with gcc mygrepin.c, run with ./a.out test test.txt. This is what my test.txt looks like: hallo das ist ein Test.
test
test
test
test
test

I am expecting this output for this command ./a.out test test.txt:
hallo das ist ein Test.
test
test
test
test
test


Solution

  • You try to use

    malloc(sizeof(strlen(buffer)))
    

    on an object you just defined as Null

    char * buffer = NULL;
    

    Malloc is used to allocate space. What you want to do is to allocate space for the size of a string with the length of your variable buffer. Buffer is null.

    Edit: As a comment pointed out not no space is allocated. It is either 4 or 8 depending on your machine. It works on the type. A pointer should return the value of 4 or 8 depending on your architecture of the system. Thanks to @mch for pointing that out. Even though this is true, the problem still remains and was caused by the buffer never being set to a value besides NULL.