Look at the second edit part.
I'm beginner of C (since I almost always use Python). So my question is (I can say) simple about malloc and memory...
// where the built-in malloc declared
#include <stdlib.h>
int main() {
char* data = malloc(13); // with standard malloc
}
Let say I don't want to use stdlib.h and instead I make my own code for malloc which return ONLY the memory address in a file called memory.h
void* malloc(int size) {
return (__malloc_memory += size);
}
This function malloc returns the address, where __malloc_memory is basically 6487580 [__malloc_memory is basically memory address] (tested by declaring some stuff). So, it is okay to do like this? If not, then why?
// my declaration of new malloc
#include <memory.h>
int main() {
char* data = malloc(14); // This is the new defined malloc, not the built-in one
data[0] = 'H';
// some stuff
data[12] = '!';
data[13] = '\0'; // Null terminate
printf("%s", data);
}
Output
Hello, world!
The output will return the same everytime.
EDIT 1:
// memory.h
static int __malloc_memory = 6487580;
void* malloc(int size) {
return (__malloc_memory += size);
}
And main.c
int main() {
double* name = (char*)malloc(1);
name[0] = 3.4555;
printf("%lf", name[0]);
}
OUTPUT
3.455500
EDIT 2:
This question sucks. Now I understand what I made is a very basic mistake, since now I understand how an Operating System work (and of course how to make one using Assembly, but not fully). I will not delete this question, since that is very disrespectful. [And why the heck I cast malloc [in C]...? For what I know, I never do that.] [Now (as per 07-07-2021), I would call myself a C intermediate (not expert yet).]
where __malloc_memory is basically 6487580 (tested by declaring some stuff)needs some further explanation.free()? For a beginner to C, I recommend using the standard library functions.static int __malloc_memory = 6487580;andreturn __malloc_memorymake no sense.__malloc_memoryis not memory, it's a number.6487580?__malloc_memoryand increase it bysize1before returning the value the caller will get__malloc_memory+size1and use it up to__malloc_memory+2*size1-1. This means, the firstsizebytes are unused and the nextsizebytes are used instead. If you then call again withsize2which might be smaller thansize1you will return an address within the range used by first caller. You have to idea how many bytes after__malloc_memoryare used by the previous caller.