Create and resize dynamic array without C libraries?

Is there a way to create dynamic arrays in C without using stdlib?

Malloc

a library is required stdlib.h

, I am not allowed to use this in my project.

If anyone has any ideas please share them? Thank.

+3


source to share


2 answers


malloc

is not just a library, it is how you interact with the operating system to request more memory for the current process. Well, you could request more memory and manage free / used memory yourself, but that would be wrong on many levels.

But I am inclined to believe that your project will run on some platform that does not have an operating system, right? 1 In this case, a faster solution is to first allocate statically some memory in a large global array, and every time you need memory, you ask the manager in charge of that large array.

Let me give you an example, for the sake of simplicity it will be tiny and not very functional, but this is a very good quick start.

typedef char bool;

#define BLOCK_SIZE 1024 //Each allocation must have in max 1kb
#define MAX_DATA 1024*1024*10  //Our program statically allocates 10MB
#define BLOCKS (MAX_DATA/BLOCK_SIZE)

typedef char Scott_Block[BLOCK_SIZE];

Scott_Block Scott_memory[BLOCKS];
bool Scott_used_memory[BLOCKS];

void* Scott_malloc(unsigned size) {
    if( size > BLOCK_SIZE )
        return NULL;
    unsigned int i;
    for(i=0;i<BLOCKS;++i) {
        if( Scott_used_memory[i] == 0 ) {
            Scott_used_memory[i] = 1;
            return Scott_memory[i];
        }
    }
    return NULL;
}

void Scott_free(void* ptr) {
    unsigned int pos = ((char*)(ptr)-Scott_memory[0])/BLOCK_SIZE;
    printf("Pos %d\n",pos);
    Scott_used_memory[pos] = 0;
}

      



I wrote this code to show you how to emulate a memory manager. Let me point out a few improvements that can be made with it.

First, Scott_used_memory can be a bitmap instead of an array bool

. Secondly, it does not allocate more memory than BLOCK_SIZE, it must search for blocks of whole blocks to create a larger block. But for that, you need more management data to determine how many blocks the dedicated one allocates void*

. Third, searching for free memory (linearly) is very slow, usually blocks create a free block reference list.

But as I said, this is a great quick start. And depending on your needs, this can accomplish it very well.

1 If not, then you have absolutely no reason not to use malloc.

+8


source


Why not this program (C99)

#include <stdio.h>

int main(int argc, char *argv[])
{
   int sizet, i;
   printf("Enter size:");
   scanf("%d",&sizet);
   int array[sizet];
   for(i = 0; i < sizet; i++){ 
     array[i] = i;
   }
   for(i = 0; i < sizet; i++){
     printf("%d", array[i]);
   }
   return 0;
}

      



Like a boss!: -)

+2


source







All Articles