N
nfwavzrdvwl
Hi all,
This is my first posting on this forum! I hope it will be the first of
many as I work my way up to be a C guru
We had an assigment to write our own storage allocator, and mine was
graded very poorly with comment "Hopelessly naive". Now I can see the
main problem, which is that some calls to myfree() won't actually
release the memory, but that would be pretty difficult to achieve, and
the rest of it seems to work fine to me.
If anyone here can make any constructive comments, that would be great
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#define SYSTEM_RAM ( 1<<30 )
#define MAX_TO_USE ( ((SYSTEM_RAM) / 3) * 2 )
static char heap[MAX_TO_USE];
static char *p=heap;
static char *oblivion=heap+MAX_TO_USE;
static char *last;
void *mymalloc(long bytes)
{
if(p+bytes<oblivion) {
last=p;
p+=bytes;
return (void *) last;
}
return NULL;
}
void myfree(void *q)
{
if(q==NULL)
return;
if(q==last) {
p=last;
last=NULL;
return;
}
/* need something more sophisticated - we don't have it, so
* let's just leak the memory */
return;
}
int main()
{
char *t=mymalloc(14);
strcpy(t,"Hello, world!");
printf("%s\n", t);
myfree(t);
return 0;
}
This is my first posting on this forum! I hope it will be the first of
many as I work my way up to be a C guru
We had an assigment to write our own storage allocator, and mine was
graded very poorly with comment "Hopelessly naive". Now I can see the
main problem, which is that some calls to myfree() won't actually
release the memory, but that would be pretty difficult to achieve, and
the rest of it seems to work fine to me.
If anyone here can make any constructive comments, that would be great
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#define SYSTEM_RAM ( 1<<30 )
#define MAX_TO_USE ( ((SYSTEM_RAM) / 3) * 2 )
static char heap[MAX_TO_USE];
static char *p=heap;
static char *oblivion=heap+MAX_TO_USE;
static char *last;
void *mymalloc(long bytes)
{
if(p+bytes<oblivion) {
last=p;
p+=bytes;
return (void *) last;
}
return NULL;
}
void myfree(void *q)
{
if(q==NULL)
return;
if(q==last) {
p=last;
last=NULL;
return;
}
/* need something more sophisticated - we don't have it, so
* let's just leak the memory */
return;
}
int main()
{
char *t=mymalloc(14);
strcpy(t,"Hello, world!");
printf("%s\n", t);
myfree(t);
return 0;
}