1

I want to get first char character of each string. Here a example:

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

int main() {
    int size = 2;
    char** text = (char**) malloc(sizeof(char*) * size);
    for(int i = 0; i < size; ++i) {
        char buf[80];
        fgets(buf, 80, stdin);
        text[i] = (char*)malloc(strlen(buf));
        strcpy(text[i], buf);
    }

    for(int i = 0; i < strlen(text[i]); ++i) {
        printf("%c ", text[i][0]);
    }

}

In last for loop, program falls in Segmentation fault. I dont know why.

0

1 Answer 1

1

The strlen function returns the number of characters in the given string not including the terminal nul character; however, the strcpy function copies all characters including that terminating nul!

So, your allocation for text[i] is not quite big enough and, by writing beyond the buffer's bounds, you are getting undefined behaviour.

Add an extra character to the malloc call:

    for(int i = 0; i < size; ++i) {
        char buf[80];
        fgets(buf, 80, stdin);
        text[i] = malloc(strlen(buf) + 1); // Need space for the terminal nul!
        strcpy(text[i], buf);
    }

Or, more simply, use the strdup function, which achieves the same result as your malloc and strcpy in one fell swoop:

    for(int i = 0; i < size; ++i) {
        char buf[80];
        fgets(buf, 80, stdin);
        text[i] = strdup(buf);
    }

Either way, don't forget to call free on all the buffers you allocate.

EDIT: You are also using the wrong 'limit' in your final output loop; this:

    for(int i = 0; i < strlen(text[i]); ++i) { // strlen() is not the # strings
        printf("%c ", text[i][0]);
    }

Should be:

    for(int i = 0; i < size; ++i) { // "size" is your number of strings!
        printf("%c ", text[i][0]);
    }
Sign up to request clarification or add additional context in comments.

4 Comments

i add +1 at malloc and doesn't work, same as strdup. And yes, i know about free i just drop it out of snippet. onlinegdb.com/Sy12R54cL
But you still have for(int i = 0; i < strlen(text[i]); ++i) { in your second loop. See the "EDIT" part of my answer, and change that to for(int i = 0; i < size; ++i) {.
@Georgii, minor issue, casting malloc is unnecessary in C.
@anastaciu Good call! I'm normally quite pedantic about that, but somehow missed it today.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.