Thread: I am totally PuZZelEd

  1. #1
    Registered User
    Join Date
    Oct 2001

    Red face I am totally PuZZelEd

    I am 100% puzzled about pointers....
    consider the following programme...

    #include <stdio.h>
    #include <mem.h>
    int main(void)
    char *name;
    name=(char *)malloc(20);
    name="Puzzled Man";
    printf("The name is %s",name);

    free(name); //memory is free

    printf("the variable is %s",name);

    /* if there is no memory allocated for the pointer then where the value is coming from???*/

    return 0;

    Pls help me........

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    I've moved this to the 'C' board where it belongs

    > #include <mem.h>
    Malloc is declared in stdlib.h, unless you have a really old (and non-ANSI) compiler, which I would suggest you upgrade if this is the case

    > char *name;
    Good so far

    > name=(char *)malloc(20);
    OK, but you should remove the cast (which is hiding the fact that you haven't declared malloc properly)

    > name="Puzzled Man";
    Wrong - you've just lost the memory you've allocated.
    All you've done here is update the pointer (name), with the pointer to the start of your string constant.

    strcpy( name, "Puzzled Man" );
    Is the way to actually copy a string from one place to another.

    > printf("The name is %s",name);

    > free(name); //memory is free
    This should not have worked given your current code

    > printf("the variable is %s",name);
    This works anyway, because name is pointing directly at your string constant, not the malloc'ed memory.
    Even if you fix it (use strcpy), it might still work, but it would be illegal to do so - you can't refer to memory you've free'ed, because it could be re-used at any time.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2001

    Thanx a Lot!!!

    Thanx a lot!!!!
    I think i have found my problems i was far.
    No more Problems again!!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 03-09-2011, 06:38 AM
  2. Totally lost beginner
    By burrissa in forum C Programming
    Replies: 7
    Last Post: 03-29-2004, 08:00 PM
  3. i'm totally lost
    By jlmac2001 in forum C++ Programming
    Replies: 5
    Last Post: 02-01-2003, 11:06 PM
  4. Totally puzzling IO problem
    By Vorok in forum C++ Programming
    Replies: 5
    Last Post: 01-06-2003, 07:10 PM
  5. Everyone look at my totally sweet spaceship
    By Shadow12345 in forum Game Programming
    Replies: 4
    Last Post: 09-30-2002, 02:27 PM