Thread: free memory

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    41

    free memory

    /* how would I go about freeing the memory assigned in the loop
    for the nodes*/

    #include<string.h>
    #include<iostream.h>
    #include<conio.h>
    #include<stdlib.h>
    #define MAX 30

    struct node{
    int age;
    char name[MAX];
    node *next;
    };


    int main()
    {
    int amount;

    cout<<"How many people to be stored";
    cin>>amount;
    /* ptr is of type node its assigned the starting address of */
    node *ptr=(node*)malloc(sizeof(node)); /* a block of memory the size of node */
    /* malloc must be cast in c++ and not in c */
    strcpy(ptr->name,"ANTHONY");
    cout<<ptr->name;

    for(int start=0;start<amount;start++)
    {
    ptr->next=(node*)malloc(sizeof(node));
    ptr=ptr->next;
    }
    ptr=NULL;

    getch();

    return 0;
    }

    /* thanks for all the help */

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Try calling free() on each node pointer and watch for the node where next == NULL as that will be the end of the list..

    That might be difficult though as every "ptr=ptr->next;" allocates to the same next pointer and so you will be allocating structures to which you have no pointer

    Also....as you are using C++ try use the new and delete operators instead of the malloc and free functions
    Last edited by Fordy; 04-12-2002 at 05:42 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with shared memory shmdt() shmctl()
    By Jcarroll in forum C Programming
    Replies: 1
    Last Post: 03-17-2009, 10:48 PM
  2. Replies: 7
    Last Post: 02-06-2009, 12:27 PM
  3. How to Free All Memory ?
    By sergioms in forum C Programming
    Replies: 52
    Last Post: 01-15-2009, 05:02 PM
  4. Memory leak with detached pthreads - how to free?
    By rfk in forum Linux Programming
    Replies: 2
    Last Post: 08-17-2007, 06:50 AM
  5. free memory in structure
    By franziss in forum C++ Programming
    Replies: 22
    Last Post: 01-08-2007, 05:16 PM