BSalunke
BSalunke

Reputation: 11737

Unexpected output when uses getline() to read entire line from stdin?

I'm working on c, following is my code:

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

int main()
{
        char* str = NULL;
        size_t n;

        printf("Enter the string : \n");
        getline(&str, &n, stdin);
        printf("Initial string is : (%s)\n", str);
        return 0;
}

When i run the above program it gives following output:

Enter the string :
bsalunke
Initial string is : (bsalunke
)

What might be the reason of unexpected string getting stored in str pointer(i.e. it is a string with many white spaces) ? Im using gcc 4.1.2 version on linux

Upvotes: 2

Views: 639

Answers (2)

Lundin
Lundin

Reputation: 214780

The program does not work because you are writing code which you don't understand. You cannot "store a string in a pointer". You need to study arrays and pointers.

You are attempting to store data at a random memory location, without allocating any memory for the data. This is completely undefined behavior.

Upvotes: 0

uba
uba

Reputation: 2031

From the man page of getline

getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.

I think that explains it. It is not a string with many white spaces, it is a string ending with a new line.

Upvotes: 5

Related Questions