Lines and Pointers

#include<string.h> #include<stdio.h> int main() { char *p; strcpy(p,"hello world"); } 

Ok, does this show undefined behaviour or indicate a world of welcome? I saw many programmers using this kind of sytax.I know it better than an array where you don't know the size of the string. But it’s good to use in programming. Can anyone explain this?

+4
source share
6 answers

This behavior is undefined as p not initialized. I don’t think that you really see a lot of people who do this ...

strcopy expects a buffer of sufficient length to copy the contents of the second argument to. Your example is intentionally contrived, but in real code you need to know the size of source_string to allocate a buffer.

+4
source

You did not initialize p , so the behavior is clearly undefined. If you initialize p to indicate an area with enough space to store the string, or you assign (not strcpy() ) "hello world" - p (thereby pointing to the area in the initialized program memory where the literal string is) or you use strdup() instead of strcpy() , it will work.

+2
source

I have seen many programmers using this kind of syntax.

I doubt. Perhaps with some of this syntax, but not with this semantics, that is, not without "p", pointing to a memory area large enough to hold a string, including its final null byte.

+1
source

The code you posted is completely wrong and can cause your program to crash, and it's hard to imagine that you often see this code.

Most likely, you will see a code similar to the following.

 int main() { char *p = (char*)malloc(20); strcpy(p, "hello world"); free(p); } 
+1
source

You do not need to select and copy to get a string. You can simply let the compiler do all the work for you:

 char p[] = "Hello world!"; 

And he will even calculate the correct size of the array!

+1
source

p is not initialized, and copying anything to it will lead to Segmentation Fault and unpredictable results, because the memory location indicated by p is not indicated by the code.

Before you can copy a string to p, you must point to the memory pointed to by p.

you must use char [Buffersize];
for example char [12];

0
source

All Articles