Search code examples
cfor-loopheap-memorydynamic-memory-allocationc-strings

Having troubles understanding string declaration in C


I'm having some trouble understanding a string declaration in C using dynamic memory.

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

char *putText(){
    
    char *s=(char *) malloc(256+sizeof(char));
    for(int i=0; *(s+i); i++) *(s+i)=getchar();
    return s;

}

void main(){
    
    printf("Write the text: ");
    char *s=putText();
    printf("%s", s);
    
}

In this function, I'm trying to declare the string using getchar() in a for loop, but when I try to print the string, it always stops at the third character. I am still a newbie, so I've probably made some mistake. Can someone help?


Solution

  • The allocated memory in this declaration

    char *s=(char *) malloc(256+sizeof(char));
    

    can contain any garbage.

    So the condition in the for loop

    for(int i=0; *(s+i); i++) *(s+i)=getchar();
    

    does not make a sense.

    Instead you could write for example

    int c;
    
    for ( size_t i=0; i + 1 < 256 && ( c = getchar() ) != EOF && c != '\n'; i++ )
    {
        *( s + i ) = c;
    }
    
    *( s + i ) = '\0';