Re: Help in c pointers



"manochavishal@xxxxxxxxx" wrote:

int *p;
*p = 4;

char * msg;
*msg = 'c';

printf("msg is %s",msg);

when i try to pass a value 4 to place what integer pointer p
points to it says seg fault but for the char pointer it works fine.

Why this behaviour

You were unlucky with the char pointer.

Neither p nor msg points anywhere. Trying to dereference either of
them results in undefined behavior. Undefined behaviour includes
"working". It also includes launching flying pigs.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>


.



Relevant Pages

  • Re: pointer and storage
    ... I always thought that where the string literals are stored ... it invokes undefined behavior. ... pointer is unconditionally bad, ... "hello" is not const char *. ...
    (comp.lang.c)
  • Re: Help in c pointers
    ... char * msg; ... and both assignments invoke UB. ... there's a third instance of undefined behavior here - ... `msg' isn't a c-string so ...
    (comp.lang.c)
  • Re: Comments ok?
    ... and the resulting undefined behavior may have caused `p' to ... Could it be a single char, an unitialised pointer, ... the caller will provide an ...
    (comp.lang.c)
  • Re: doubt on char *
    ... char *destbuf; ... destbuf is uninitialized. ... This is one reason for those who advocate initialising all pointer ... Dereferencing a NULL pointer invokes undefined behavior. ...
    (comp.lang.c)
  • Re: Help in c pointers
    ... but for the char pointer it works fine. ... your particular case, the address in p happened to be invalid for an int, ... and the address in msg happened to be valid for a char, ...
    (comp.lang.c)