Search code examples
arrayspointerschardynamic-arrays

segmentation fault (Core dumped) error Access elements in dynamic array


I want to take a string from the user prints it out, and access its first character, but with below code I get

segmentation fault (Core dumped)

Code

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

 #define GROW_BY 10

int main(){
   char *str_p, *next_p, *tmp_p;
   int ch, need, chars_read = 0;
   if(GROW_BY < 2){
    fprintf(stderr, "Growth constant is too small\n");
    exit(EXIT_FAILURE);
}
str_p = (char *)malloc(GROW_BY);
next_p = str_p;
while((ch = getchar()) != EOF){
    if(ch == '\n'){
        printf("%s\n", str_p);  
            //Here is the error I also tried *(str_p + 0), (*str_p)[0]
        printf("%s\n", str_p[0]);
        free(str_p);
        str_p = (char *)malloc(GROW_BY);
        next_p = str_p;
        chars_read = 0;
        continue;
    }
    if(chars_read == GROW_BY - 1){
        *next_p = 0;
        need = next_p - str_p + 1;
        tmp_p = (char *)malloc(need + GROW_BY);
        if(tmp_p == NULL){
            fprintf(stderr, "No initial store\n");
            exit(EXIT_FAILURE);
        }
        strcpy(tmp_p, str_p);
        free(str_p);
        str_p = tmp_p;
        next_p = str_p + need - 1;
        chars_read = 0;
    }
    *next_p++ = ch;
    chars_read++;
}
exit(EXIT_SUCCESS);

}


Solution

  • str_p[0] is a character not string

    so you should use %c

    printf("%c\n", str_p[0]);
    

    This happens because there is no type-safety for the variable arguments, in printf(), if the format specifier is wrong, the code will read invalid results from memory, possibly crashing.

    One useful tip to help you in debugging is to enable compiler warnings for example in GCC:

    gcc -Wall main.c -o main
    

    this will show you the following warning for your program.

    warning: format specifies type 'char *' but the argument has type 'char' [-Wformat]
            printf("%s\n", str_p[0]);
                    ~~     ^~~~~~~~
                    %c
    1 warning generated.
    

    Its highly recommended to use -Wall flag to catch some this trouble in your program.