박호연
박호연

Reputation: 1

why segmentation fault in c and how to make it work?

#include "stdio.h"

void save(char* savefile, char ch);

int main()
{
        char* savefile = {0};
        char ch;
        scanf("%c", &ch);
        printf("%s\n", savefile);

        return 0;
}

void save(char* savefile, char ch)
{
        savefile[strlen(savefile)] = ch;
}

so i was trying to make a program that saves what i typed. And i can't get why it isn't working. i'm guessing that changing savefile is the messy part.

Upvotes: 0

Views: 62

Answers (2)

Akib Azmain Turja
Akib Azmain Turja

Reputation: 1190

Because your char array is NULL

You called printf with a char array, whose value is NULL, leading to undefined behavior and segmentation fault. First, give savefile some valid value, then try again, it should work.

Upvotes: 0

4386427
4386427

Reputation: 44340

The main problem is that savefile is a pointer initialized to NULL so when you call printf("%s\n", savefile); you pass a NULL pointer. Then printf dereferences the NULL pointer and you get a crash.

Instead you want savefile to be an array of chars so that it can hold a C-style string.

Your code is kind of strange as you never call the function save. Maybe you want something like:

#define MAX_LEN 32

int main()
{
        char savefile[MAX_LEN + 1] = {0};   // Make savefile an array of
                                            // (MAX_LEN + 1) chars. All 
                                            // initialized to zero
        char ch;
        scanf("%c", &ch);
        save(savefile, ch);                 // Call the function
        printf("%s\n", savefile);

        return 0;
}

void save(char* savefile, char ch)
{
    size_t len = strlen(savefile);
    if (len < MAX_LEN )
    {
        savefile[len] = ch;
    }
}

Upvotes: 1

Related Questions