I am writing my own OS and had to implement my own malloc realloc functions. However I think that what I have written may not be safe and may also cause a memory leak because the variable isn't really destroyed, its memory is set to zero, but the variable name still exists. Could someone tell me if there are any vulnerabilities in this code? The project will be added to github soon as its finished under user subado512.
Code:
void * malloc(int nbytes)
{
char variable[nbytes];
return &variable;
}
void * free(string s) {
s= (string)malloc(0);
return &s;
}
void memory_copy(char *source, char *dest, int nbytes) {
int i;
for (i = 0; i < nbytes; i++) {
*(dest + i) = *(source + i); // dest[i] = source[i]
}
}
void *realloc(string s,uint8_t i) {
string ret;
ret=(string)malloc(i);
memory_copy(s,ret,i);
free(s);
return &ret;
}
Context in which code is used : Bit of pseudo code to increase readability
string buffstr = (string) malloc(200);
uint8_t i = 0;
while(reading)
{
buffstr=(string)realloc(buffstr,i+128);
buffstr[i]=readinput();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…