-4

Could anybody help to explain why running the execution file (built from the following C program using Dev-C++ 5.6.3) causes crash? There are some explanation in Pradip Dey and Ghosh Manas 2013 Computer fundamentals and programming in C that says "Location 1000 might contain the program. Since it is a read only, the operating system will throw up a segmentation fault. What about *pi = 5? Again, it will most likely cause a segmentation fault because lower memory addresses are typically used for program code. This area is only read. It should be known in advance where this constant is located in the memory."

However, to me, these explanation are difficult to understand

int main()
{
    int *ip;

    ip = (int*)1000;
    *ip = 5;
}
ICTer
  • 1
  • 3

2 Answers2

2

In most cases a pointer is just an address of data in memory. There are certain considerations about which addresses of memory are accessible and which are not, which addresses are are used by code and by data, ... the memory space is segmented, meaning that some address are not even available.

you have declared a pointer int *ip; Then you assigned it a value of 1000. The latter is supposed to be an address of some data in memory. Why 1000? it could be a memory address which is inaccessible or a memory address of a some other data or a memory address of code of your program. In general, unless you write an system-level software, you cannot do any assumption about hard-coded addresses in memory. You can only rely on the addresses provided by your program. So, your attempt to assign a value to the memory of address 1000 ended up in a segmentation fault, meaning this address is not available for you.

There are several ways to use pointers correctly.

1) use an address of an existing variable:

 int var;
 int *ip = &var;
 *ip = 5;

2) use an address of dynamically allocated memory returned to you, say by malloc

 int *ip = malloc(sizeof(int));
 *ip = 5;
 ...
 free(ip);
Serge
  • 11,616
  • 3
  • 18
  • 28
0

But the following assignment appears to be OK:

char *ptr;

ptr = "Input a string: ";
printf("%s", ptr);

There are some differences between r-value of numeric type and that of string?

Actually I found this helpful: In C, why can't an integer value be assigned to an int* the same way a string value can be assigned to a char*?

ICTer
  • 1
  • 3