Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings and pointers

Tags:

c

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?

like image 243
cody Avatar asked Jan 19 '23 07:01

cody


1 Answers

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.

like image 176
Ed S. Avatar answered Jan 28 '23 00:01

Ed S.