简体   繁体   中英

Why do I get 'Segmentation fault (core dumped)'?

I am making a program that has the user enter in a line of text, and the program then prints it back to them. They way I have done it - more specifically with the char *read_line() method - is in a way I have to for my homework.

When the user enters in something (such as their name) and presses enter, it just says, 'Segmentation fault (core dumped)' and I don't know why.

#include <stdio.h>

char *read_line(char *buf, size_t sz)  {
    if (fgets(buf, sz, stdin) && buf[0] != '\n' ) 
    {
        return buf;
    }
    else
    {
        return NULL;
    }
}

int main(int argc, char** argv) {
    char *buf;
    char *p;

    p = read_line(buf, 1024);

    if (p != NULL) {
        fputs(p, stdout);
    }

    return 0;
}
char *buf;

You've declared a pointer to a char here, but have not initialized it. Therefore, it's value is whatever was on the stack when your function is called.

When you attempt to access the memory it points to, which is some random memory address, that's almost certainly going to be an illegal memory access.

Either use malloc() to allocate some memory to point to (don't forget free() ), or set the variable to the address of another variable.

The simplest thing you can do is change the following:

char buf[1024];
p = read_line(buf, sizeof(buf));

As an alternative, you can do the following:

char *buf;
p = read_line(&buf, 1024);

char *read_line(char **buf, size_t sz)
{
    *buf = malloc(sz);
    ...
}

If you use this method, don't forget to free .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM