简体   繁体   中英

Strings and pointers

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

int main()
{        
    char *p;         
    strcpy(p,"hello world");
}

Well,Does it show undefined behaviour or Does it point to hello world? I have seen many of the programmers using these kind of sytax.I know its better than an array where you dont know the size of string.But is it good to use in the programming.can anyone explain it?

That is undefined behavior as p is uninitialized. I don't imagine you actually see a lot of people doing that...

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

You didn't initialize p , so the behavior is explicitly undefined. If you initialize p to point to an area with sufficient space to hold the string, or you assign (not strcpy() ) "hello world" to p (thus pointing it to the area in initialized program memory where the literal string is stored), or you use strdup() instead of strcpy() , it will work.

I have seen many of the programmers using these kind of syntax.

I doubt it. Maybe with some of that syntax, but not with these semantics, ie not without 'p' pointing to an area of memory large enough to hold the string, including its trailing null byte.

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

You are more likely to see code like the following.

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

You don't have to allocate and copy to get a string. You can just let the compiler do all the work for you:

char p[] = "Hello world!";

And it will even compute the proper size for the array!

p is uninitialized and copying anything to it will produce Segmentation Fault and unpredictable results because the location in memory that p is pointing to is not specified by the code.

Before you can copy a string to p, you must specify the memory that p is pointing to.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM