0

When I try to pass a malloc'd char pointer from main to use in user_input to get a string in it. After the while loop is done I'm trying to print filename. filename ends up to be empty when it should contain a valid string.

void user_input(char *filename){
    char ch;

    int i = 0;

    printf("Fil att leta i: ");
    while((ch = getchar()) == '\n'){
        filename = realloc(filename, (i+1) * sizeof(char));
        filename[i] = ch;

        i++;
    }
    filename[i] = '\0';
    printf("filnamn = %s", filename);

}

int main(void){
    char *filename;

    filename = (char *)malloc(sizeof(char));
    user_input(filename);

    return 0;
}
1
  • You know, sizeof(char) is defined as 1. There's absolutely no reason to ask whether a char is more than one char big. Commented Oct 19, 2014 at 19:14

2 Answers 2

3

The filename is a pointer which is passed by value. When you do this in the user_input function

filename = realloc(filename, (i+1) * sizeof(char));

the filename in the main does not change. When you print filename in the main, the pointer has been realloced, so you trigger undefined behavior.

You need to pass filename by pointer. Since it's already a pointer, you end up with a double pointer:

void user_input(char **filenamePtr)

Now you need to take a pointer in the main

user_input(&filename);

and dereference in the user_input:

*filenamePtr = realloc(*filenamePtr, i+2);

Note that sizeof(char) is always 1, so you do not need to multiply by it. Also you add 2, not 1, to i so that you have enough space for the null terminator '\0' character.

Sign up to request clarification or add additional context in comments.

Comments

1

Change this:

while((ch = getchar()) == '\n')

into this:

while((ch = getchar()) != '\n')

you only read the \n. You should read anything but the \n.

Comments

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.