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

Can you please tell me what's wrong with this string input code block,it keeps giving segmentation fault

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
    char *str;
    int len;
    printf("Enter the expression: \n");
    scanf("%[^\n]", &str);
    printf("%s\n", str);
    len = strlen(str);
    printf("%d\n", len);
}

I am trying input a string into a string pointer but it keeps giving me a segmentation error, however when i initialize it as char array it works fine.

>Solution :

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

It looks like you are trying to get scanf to allocate the necessary memory for the string. That option is only available as an extension in some implementations, but here’s how that would work:

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

int main(void) {                        // note the proper declaration
    char *str = NULL;
    int len;
    printf("Enter the expression: \n");
    if(scanf("%m[^\n]", &str) == 1) {   // add `m` to malloc memory for the string
        printf("%s\n", str);
        len = strlen(str);
        printf("%d\n", len);
        free(str);                      // and `free` it after use
    }
}
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