Is This Supposed To Happen? [Dynamic Memory]

This is a discussion on Is This Supposed To Happen? [Dynamic Memory] within the C Programming forums, part of the General Programming Boards category; I'm calling the following function: Code: unsigned int Test(void) { char *var; var = (char*) malloc(255); memset((void*)var,0,254); strcpy(var,"A string."); free(var); ...

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    27

    Is This Supposed To Happen? [Dynamic Memory]

    I'm calling the following function:

    Code:
    unsigned int Test(void)
    {
        char *var;
        
        var = (char*) malloc(255);
        memset((void*)var,0,254);
        
        strcpy(var,"A string.");
        
        free(var);
        
        MessageBox(NULL,var,"Data in var",MB_OK);
        
        return 0;
    }
    And, for some reason, even though it's been free()'d, I'm still getting this: (see attachment).

    Is this supposed to happen? o_O
    Attached Images Attached Images  

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    You can get anything and everything by using freed memory. All this means is that either (a) the memory has yet to be reassigned and/or (b) the new owner hasn't written new stuff in it yet. The memory is not trashed when freed.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    27
    Oh, that makes sense. Thanks p_o

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    A free pointer still points to the same address. You could use var=NULL.

    ps. your memset does not need to be one byte smaller than your malloc, since they both refer to the number of (not "the count beginning with zero").
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. magic could happen on recvfrom
    By -EquinoX- in forum C Programming
    Replies: 22
    Last Post: 03-27-2009, 07:06 PM
  2. Is what I think is gonna happen gonna happen
    By cunnus88 in forum C++ Programming
    Replies: 2
    Last Post: 02-04-2009, 10:34 PM
  3. I don't think this is supposed to happen.
    By Mako Eyes in forum C++ Programming
    Replies: 13
    Last Post: 11-03-2002, 07:29 PM
  4. What would happen?
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 04-04-2002, 10:54 AM
  5. Replies: 4
    Last Post: 03-04-2002, 03:37 PM

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