Manual malloc

I tried to code malloc function manually but it didn't work.Suppose I want to allocate 3 int (means 12 byte) and than print them. First integer is correct but rest are wrong.I couldn't find the mistake..

#include <stdio.h>
#define ALLOCSIZE 30
int * func(int);
int main ()
{

int num,i;
int *ptr;

printf("How many students do you have ?\n" );
ptr=func(scanf("%d",&num));

for(i=0;i<num;i++)
scanf("%d",(ptr+i));
for(i=0;i<num;i++)
printf("%d ",*(ptr+i));

return 0;
}

int *func (int num)
{

int array[ALLOCSIZE];
int *ptr=array;

if(ALLOCSIZE>=num)
{
ptr+=num;
return ptr-num;
}
else
return 0;

}

You can't write a malloc() just like that. malloc() is a complex, low level, system-dependent function.

The array declared in func() is allocated in the stack, and is popped (i.e. deallocated) when the function returns. You're in risk of smashing the stack by using that function.
The only way to return a pointer to valid memory that doesn't go out of scope is by dynamically allocating the memory. You do this by using malloc() or the 'new' operator. new, of course, uses malloc().

I only have a superficial understanding of how the function works, so I couldn't tell you how to write one. The more experienced members might know.
You could start by looking at an implementation of gcc.
Topic archived. No new replies allowed.