seems like I never need malloc to allocate memory dinamically when it comes to strings example:

 int main(void)
 {
    char *str;
    puts("keyword:");
    scanf("%30[^\n]\n",str);
    printf("%s",str);
 }

I never defined str size, yet it works

sorry if this is a stupid question it's 2 am and I'm studying for some c quiz lol

It only appears to work, it is in fact undefined behaviour, this is exactly what it says the behaviour may be a crash or it may appear to work or anything inbetween and it may do different things every time it is run. If you put this sort of code into a larger program that ran for longer you would run a very serious risk of the program crashing at some unknown point in the future.

And the moral: If you know it is wrong don't do it just because it "appears to work", do it the right way.

I never defined str size, yet it works

It crashes miserably and consistently for me. I guess "works" is a pretty loosely defined term. ;)

So it's always incorrent to use a pointer to represent a string?

So it's always incorrent to use a pointer to represent a string?

No. It's always correct. It's up to you to make sure the pointer is pointing at the right memory to put the chars in.

Edited 3 Years Ago by Moschops

It's always incorrect to use a pointer that doesn't point to valid memory to do anything at all.
It's perfectly correct to take a pointer that points to valid memory containing a 0-terminated sequence of characters and pass that to a function that expects a string.

This article has been dead for over six months. Start a new discussion instead.