-2

i know that before dereferencing any pointer variable it should points to valid memory location otherwise segmentation fault will occur such as this code example

int *ptr = 10;
int y = *ptr; 

My question is what is meant by segmentation error and how to avoid it ?

Elhaw
  • 325
  • 3
  • 18
  • That code won't compile at all. – Brian Bi Mar 03 '15 at 22:07
  • `what is meant by segmentation error` That you´re accessing a memory segment now owned by you (or invalid altogether). `how to avoid it` DOn´t do things like in your example. – deviantfan Mar 03 '15 at 22:09
  • There's no guarantee that dereferencing an invalid pointer will cause a segfault. – chris Mar 03 '15 at 22:11
  • [Explanation of segmentation error from wikipedia](http://en.wikipedia.org/wiki/Segmentation_fault). Avoid segmentation errors by initializing pointers correctly. Also, always compile with all warnings, `-Wall` when using `gcc`, and fix everything. Never ignore compiler warnings. – user3386109 Mar 03 '15 at 22:15
  • just to help you out in the future for getting help on this website. http://stackoverflow.com/help/how-to-ask – SorryEh Mar 03 '15 at 22:32

1 Answers1

1

A segmentation violation occurs when your program tries to access a memory address that it doesn't have permission to. This can be:

  • Memory regions that haven't been allocated to the process at all
  • Memory regions that are reserved for the kernel to use
  • Memory regions whose protection does not include the operation you tried (e.g. writing to read-only memory).

This most often occurs when you try to dereference a pointer that hasn't been initialized properly. Except in special circumstances, the proper ways to initialize a pointer are:

  • Taking the address of some other variable, e.g. ptr = &var;.
  • Allocating dynamic memory: malloc/realloc in C, new in C++
  • Assigning it from some other pointer variable that has been initialized properly.

You can also add and subtract from valid pointers to get new pointers. This pointer will be valid so long as you stay within the size of the object that the pointer was originally derived from. However, if you go outsize these bounds, you may or may not get a segmentation violation. Most often, you'll just access some adjacent object in memory, causing program bugs but not a signal.

Initializing a pointer from a integer, e.g. int ptr = 10;, does not have defined behavior, but in most implementations it just tries to use this virtual memory address. Since most operating systems use low-numbered addresses for the kernel, this will usually result in a segmentation violation error.

Barmar
  • 741,623
  • 53
  • 500
  • 612