int * p = (void *) 1; /* seg fault. why is this happening ? */
Printable View
int * p = (void *) 1; /* seg fault. why is this happening ? */
Do you actually expect "1" to be a valid memory address?
The first MiByte of RAM in modern PCs is always reserved by the system for special purposes (old device support, for example).
/*more specific*/
Code:int * ptr = (void*) 1;
printf("The value of ptr is %i\n",ptr); /*why this is legal*/
printf("The value of ptr is %ls\n",ptr); /*why this is seg fault*/
Are you trying to learn C just by trying stuff to see what crashes and what doesn't?
The problem with this approach is there is no guarantee of failure when you do something wrong.
> printf("The value of ptr is %ls\n",ptr); /*why this is seg fault*/
Not only is it dumb to try and dereference an int pointer to random memory locations, it's even dumber still to try and print it as a string.
This about summarises what you can do with an int pointer in a typical user-space program running on any common OS.
Code:#include <stdio.h>
#include <stdlib.h>
int main ( ) {
struct foo {
int bar;
} structvar;
int arrayvar[10];
int intvar;
int *ptr;
ptr = NULL; // valid, but you can't dereference it
ptr = &intvar; // *ptr is valid
ptr = arrayvar; // *ptr is valid, as is ptr[0] tru ptr[9]
ptr = &arrayvar[0]; // *ptr is valid, as is ptr[0] tru ptr[9]
ptr = &arrayvar[5]; // *ptr is valid, as is ptr[0] tru ptr[4]
ptr = &arrayvar[10]; // valid, but you can't dereference it.
// You can however use <, != comparisons with another
// ptr to the same array
ptr = &structvar.bar; // *ptr is valid
ptr = malloc( sizeof(*ptr)); // *ptr is valid
free(ptr); // Only free what malloc returned.
}