Thread: Seg Fault on Trivial Pointer assignment?

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    7

    Seg Fault on Trivial Pointer assignment?

    Hi,
    I am compiling the following simple program on g++ under cygwin:
    insert
    Code:
    #include<stdlib.h>
    
    using namespace std;
    
    int main()
    {
    	int *p;
    	*p = 0;
    }
    The compilation is fine, but I get a seg fault on the line *p = 0 at run-time and I have no idea why.

    GDB gives:
    Starting program: /home/David/basic.out
    Loaded symbols for /cygdrive/c/WINDOWS/system32/ntdll.dll
    Loaded symbols for /cygdrive/c/WINDOWS/system32/kernel32.dll
    Loaded symbols for /usr/bin/cygwin1.dll
    Loaded symbols for /cygdrive/c/WINDOWS/system32/advapi32.dll
    Loaded symbols for /cygdrive/c/WINDOWS/system32/rpcrt4.dll

    Program received signal SIGSEGV, Segmentation fault.
    0x0040107d in main () at basicTest.c:8
    8 *p = 1;


    Any help would be greatly appreciated.

    Thanks,
    Dave.

  2. #2
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    Well, you haven't assigned your pointer yet, so you aren't suppose to dereference it.

    int* p; declares a pointer that can point to an int. But it isn't yet

    *p = 0; "goes" to the address in memory being pointed by p and changes the value to 0. But p isn't pointing to anything yet.

    int a = 13;
    int* p;
    p = &a; // <-- there. Now it works. I told p to point to the address of a
    *p = 0; // a now has the value 0
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    7
    Thank you!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 10-15-2008, 09:24 AM
  2. Thread Prog in C language (seg fault)
    By kumars in forum C Programming
    Replies: 22
    Last Post: 10-09-2008, 01:17 PM
  3. seg fault
    By hka26 in forum C++ Programming
    Replies: 1
    Last Post: 10-08-2007, 01:38 AM
  4. Seg Fault Problem
    By ChazWest in forum C++ Programming
    Replies: 2
    Last Post: 04-18-2002, 03:24 PM
  5. seg fault on unix platform
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 12-08-2001, 12:04 PM