cody
cody

Reputation: 137

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?

Upvotes: 4

Views: 118

Answers (6)

Bo Persson
Bo Persson

Reputation: 92381

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!

Upvotes: 1

Jonathan Wood
Jonathan Wood

Reputation: 67345

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);
}

Upvotes: 1

user207421
user207421

Reputation: 311047

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, i.e. not without 'p' pointing to an area of memory large enough to hold the string, including its trailing null byte.

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124790

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.

Upvotes: 4

geekosaur
geekosaur

Reputation: 61457

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.

Upvotes: 2

Vishwanath Dalvi
Vishwanath Dalvi

Reputation: 36671

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];

Upvotes: 0

Related Questions