dynamic array malloc()

This is a discussion on dynamic array malloc() within the C Programming forums, part of the General Programming Boards category; This code requests some heap memory with the initial buffer size of 10. If the user enters 10 or less ...

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    4

    Question dynamic array malloc()

    This code requests some heap memory with the initial buffer size of 10.
    If the user enters 10 or less items, I'm ok.

    but let's say he enters 4. Although I free() the array later on, I think wasted some memory because I had malloc() with size 10 already.

    I know if I go over 10, the program will give me garbage.

    How can I avoid setting up the initial buffer size?
    How can I make an array truly dynamic? I just initiate with size 1, if I have more entries, the array expands automagically.


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h> 
    
    #define STARTOFF 10
    
    int main (void){
    	double *numbers;
    	double *temp_nums;
    	
    	int i = 0;  
    	char response;
    	
    	int count;
    	
    	numbers = (double *)malloc(STARTOFF * sizeof(double)); 
    
    	if (numbers == 0){
    		printf("Out of memory!\n");	
    		exit(1);
    	}
    	
    	printf("Do you want to enter a number (y/n)? ");
    	response = getchar(); 
    
    	while (toupper(response) == 'Y'){
    		printf("Enter a number: ");
    		scanf("%lf", &numbers[i]); 
    		i++; 
    		fflush(stdin);
    		printf("Do you want to enter a number (y/n)? ");
    		response = getchar(); 
    
    
    	}
    	
    
        count = i;
        
        temp_nums = (double *)malloc(count * sizeof(double));
    
        for (i = 0; i < count; i++){
        	temp_nums[i] = numbers[i];	
        }
    
    
           free(numbers);
    	
    	
    	numbers = temp_nums;
    	
    
    	free(temp_nums);
    	
    
    	printf("\nNumbers entered");	
    	
    	for (i = 0; i < count; i++){
    		printf("\n%.2f", numbers[i]);	
    	}
        
            printf("\n");
    	return 0;	
    }

  2. #2
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,263
    There's nothing "automagic" about C... You need to constantly check if the array is large enough to hold a new item. If it isn't, you need to expand it with realloc(). You can put this stuff in functions to make it easier to use.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Code Abuser
    Join Date
    Jan 2009
    Posts
    16
    >How can I make an array truly dynamic?
    Either use a data structure that's more forgiving for growing and shrinking (e.g. a linked list), or if performance is really an issue, you'll just have to reallocate the entire array every time.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Before discussing the how to solve your problem, let's point out a few other problems...

    Code:
          free(numbers);
    	
    	
    	numbers = temp_nums;
    	
    
    	free(temp_nums);
    You do not want to free temp_nums, as that is what numbers point at - so you are essentially freeing the numbers you are going to use.

    Code:
    		fflush(stdin);
    Is a bad idea - fflush() is not defined for input streams, so what happens when you call it is undefined - it may do what you want, or it may do nothing, or it may crash the application or any other option of "working right or not working right".

    If your number of doubles really are as small as 10 or 4 or some such, I wouldn't worry about "wasting memory", as the overhead of allocating memory will probably be about the same as your actual extra memory used by malloc behind the scenes to keep track of the allocation.

    If you potentially have tens of thousands or millions of doubles, then it does make sense to have a dynamic solution, and using realloc as suggested. However, do not make the mistake of calling realloc EVERY time the array grows - make it grow by a factor, e.g. 2x, 25% larger or some such - this avoids copying the array n-times for n elements. Yes, you are wasting a little bit of memory - but not much compared to the overall size of the array [of course, if you use the "double it" method and have 2^x+1 elements, you may waste 2^x-1 elements]. This method requires that you keep track of the capacity as well as count, but the overhead of expanding the array is much larger than tracking a single extra variable.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,920
    You can actually ask how many elements you want first before mallocing...
    Otherwise, you must manually keep track of the size and expand as needed, as already stated. C offers no truly "dynamic" array.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Array Allocation function
    By P4R4N01D in forum C++ Programming
    Replies: 6
    Last Post: 05-15-2009, 03:04 AM
  2. Dynamic array help
    By Perogy in forum C Programming
    Replies: 27
    Last Post: 04-08-2009, 03:25 PM
  3. Dynamic pointer array in C
    By MacFromOK in forum Windows Programming
    Replies: 14
    Last Post: 04-09-2005, 07:14 AM
  4. Checking maximum values for dynamic array...
    By AssistMe in forum C Programming
    Replies: 1
    Last Post: 03-21-2005, 12:39 AM
  5. 2D dynamic array problem
    By scsullivan in forum C Programming
    Replies: 3
    Last Post: 12-30-2002, 10:02 PM

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