Seung Kwak Seung Kwak - 1 month ago 18
C Question

segmentation fault in c about using malloc, and char array pointer

im trying to make a program which reads what we wrote without concerning the memory, and print out what we wrote!
but it goes to segmentation fault (core dump)

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

int isdigit(char c);
int main()
{
char *input
int length;

printf("Number or Letter\n");
gets(input);
input = (char*)malloc(sizeof(char)*strlen(input));
printf(input[0]);
return 0;
}

Answer

To read in an arbitrary long input string, you must use some kind of memory re-allocation when the input string grows beyond the already allocated memory. For instance you could use realloc like this:

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

#define INCREASE 32

int main(void) {
    int c;
    int allocated = INCREASE;
    int used = 1;
    char* in = malloc(allocated*sizeof(char));
    if (!in) exit(1);
    *in = '\0';

    while((c = fgetc(stdin)) != EOF && c != '\n')
    {
        if (used > (allocated-1))
        {
            // printf("Realloc\n");
            allocated += INCREASE;
            char* t = realloc(in, allocated);
            if (t)
            {
                in = t;
            }
            else
            {
                free(in);
                exit(1);
            }
        }

        in[used-1] = c;
        in[used] = '\0';
        ++used;
    }
    printf("%s\n", in);
    free(in);
    return 0;
}