Re: Help in c pointers



On 2006-02-28, Kenneth Brody <kenbrody@xxxxxxxxxxx> wrote:
"manochavishal@xxxxxxxxx" wrote:

HI

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

Neither pointer has been initialized, and both assignments invoke UB. In
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, and didn't cause
any noticable effect by overwriting that memory.

Incidentally, there's a third instance of undefined behavior here -
anyone know what it is?
.



Relevant Pages

  • Re: Memory Structure Pointer Problems
    ... typedef struct sta { ... char* name; ... int num_cmpnds; ... A pointer to a struct cmp is almost ...
    (comp.lang.c)
  • Re: Insufficient guarantees for null pointers?
    ... will the compiler know what the bounds are after converting that char * ... to an int *, if it could point to either of two arrays which happen to ... compares equal to the original pointer. ...
    (comp.std.c)
  • Re: problem with memcpy and pointers/arrays confusion - again
    ... int line, unsigned long *total_mem) ... That's a long pointer address... ... If sizeof > sizeof which is ... if you allocate for char with sizeof < sizeof, ...
    (comp.lang.c)
  • Re: Request critique of first program
    ... Returns a pointer to an asplit_result struct (unless unable to ... Success is indicated by SUCCESS, ... const char *out_file_b, ... const long int num_lines); ...
    (comp.lang.c)
  • Re: static in [ ]
    ... void someFunc (int size, char a) ... and passing a pointer to fewer than size characters is fine. ...
    (comp.lang.c)