Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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. So no space is allocated.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading