0

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);

}

4
  • 1
    1) CString must end with NUL character ('\0'). 2) printf("%s\n", str_p[0]); : type of str_p[0] is char, not char*. printf("%s\n", str_p[0]); --> printf("%c\n", str_p[0]);
    – BLUEPIXY
    Oct 28, 2017 at 0:11
  • Well the error was that I used %s instead of %c
    – Nasser
    Oct 28, 2017 at 0:19
  • printf("%s\n", str_p); : Besides that, since the character string does not end with NUL, access occurs beyond the valid range. Pointed out in comment (1).
    – BLUEPIXY
    Oct 28, 2017 at 0:26
  • I have added it and it works great, thx alot guys I feel so dumb
    – Nasser
    Oct 28, 2017 at 0:29

1 Answer 1

1

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.

1
  • dont worry You can improve question or your answer! and extends info on it btw i will remove downvote
    – EsmaeelE
    Oct 28, 2017 at 1:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.