tags:

views:

91

answers:

3

When allocating Strings on the heap (with 'malloc'),
and initializing them with the standard input (using 'fgets),
an unnecessary newline appears between them when trying to print them (with 'printf' and %s formatting).
for example:

main()
{
    char *heap1;
    char *heap2;

    heap1=malloc(10);
    heap2=malloc(10);
    fgets(heap1,10,stdin);
    fgets(heap2,10,stdin);
    printf("%s%s",heap1,heap2);
}

with input "hi1\nhi2" produces "hi1\nhi2". compiled using gcc 4.3.4 for Debian.

+3  A: 

fgets also reads the '\n' (newline) character. You should remove it if you don't want it to print like that.

heap1[strlen(heap1) - 1] = '\0';

after you read the contents of heap1.

IVlad
If the input line is 9 characters of more in length, this will silently remove the last character from it. It's better to use `strrchr()`.
Alok
True. Unless you're sure the length of the string won't cause that to happen, either use strrchr() or check if heap1[strlen(heap1) - 1] is actually a newline.
IVlad
Thanks a lot guys!
oho-ohohohoho.
A: 

fgets is probably appending the newline. Try trimming the string you get back from fgets.

shady
+1  A: 

fgets returns the newline as part of the string.

See man 3 fgets. Specifically:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.

Kyle Butt