pointer memory

This is a discussion on pointer memory within the C Programming forums, part of the General Programming Boards category; I was wondering when you code something like Code: int *ptr; *ptr=100; Where does the the memory come from to ...

  1. #1
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926

    pointer memory

    I was wondering when you code something like
    Code:
    int *ptr;
    *ptr=100;
    Where does the the memory come from to allocate space for 100, I saw a professor say it just finds a 100 in memory and points to it but that sounds like bologna.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    In the above example, ptr is not pointing to "anything in particular", meaning that the code will attempt to put the value 100 in some random place. It depends on many different things what actually happens:
    Alternatives are:
    Is ptr a global variable? If so, it's initialized to zero, so you'll attempt to write 100 to address zero, which is a protected location in most modern OS's.

    Is ptr a local variable in a function? If so, it will take the value that happens to be where that variable is stored on the applications stack - which can be just about anything - a common value is some other stack-address or "a text-string" - the latter leads to errors such as "application blah attempted to access memory at "0x41722038".

    Some compilers generate code so that it can detect that you're trying to access an uninitialized pointer, but most of the time, it will just do something random - and it may or may not crash the application (or if you do this in a driver or kernel-code, crash the entire system!). It may even depend on what else is going on in the application - one call to the function works fine, another call from a different place, and it crashes.

    --
    Mats

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 04-04-2009, 04:45 AM
  2. Replies: 5
    Last Post: 03-23-2009, 04:44 PM
  3. Replies: 2
    Last Post: 07-11-2008, 08:39 AM
  4. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21