C snipet on char Pointers

I have small Dout. please respond.

char *p;

p=" I am a Very good boy";

Is this valid or not?

If not valid why is it so?

It is not giving any compilation error.

Thanks

Vinod

It is syntactically valid, the compiler doesn't complain because the syntax is correct in that code, but... wha't really happens there:

char *p; only allocates the sufficient memory to hold the address of the pointer but not the rest elements of the "array". What this really means?, you have a char type pointer with 4 bytes allocated but a string with more than 15 characters.

As result you will have a run time error commonly known as memory fault access, the application receives a SIGSEGV (typically Memory fault or Segmentation fault message on you shell) signal and terminates instantly.

To solve this, you should allocate memory for your string with malloc() or statically initialize the pointer doing char *p=" I am a Very good boy";

using malloc() it maybe shows like this:

char *p;

p = (char *) malloc( (size_t) 20);

sprintf(p, "%s", "I'm a very good boy");

Best regards!

actually, this's not what happens.
a pointer is in most cases is in size of a CPU register, on 32-bits machines, it's usually 32-bits, ie 4-bytes. this 4 bytes contains not data, but a value that is a memory address where the data is held. compiler will not complain, and it's very valid. what happens is, p will get the beginning address of the constant data (usually stored in .rodata -stands for read only data- section, but may differ with the contents of linkscript) in a memory location that should behave as ROM.

yeap... you're right,
subl $24,%esp
movl $.LC0,-4(%ebp) ; .LC0, .rodata section
addl $-8,%esp

... my mistake

best regards.