1

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
dellopt
  • 23
  • 2
  • 1
    The `*(s+i)` check is reading uninitialized memory. It also does not prevent a buffer overflow, and you also don't handle `getchar` failing. – jamesdlin Dec 25 '21 at 11:03
  • 1
    First of all, for any pointer or array `s` and index `i` the expression `*(s + i)` is *exactly* equal to `s[i]`. The latter is usually easire to read and understand. Secondly, you [shouldn't really cast the result of `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Thirdly `sizeof(char)` is defined to *always* be `1`. Fourthly [`getchar`](https://en.cppreference.com/w/c/io/getchar) returns an **`int`** which is important when you compare agaionst the `int` value `EOF`. And fifhtly you should always check for `EOF`. – Some programmer dude Dec 25 '21 at 11:05
  • 1
    To continue, the `malloc` function does not initialize the memory it allocates, in any way. Its contents will be *indeterminate* and will seem random por garbage. Also always include bounds-checking in your loops, otherwise you can easily go out of bounds and have *undefined behavior*. And lastly, you never terminate the string as a proper null-terminated string. – Some programmer dude Dec 25 '21 at 11:06

1 Answers1

0

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';
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335