# include <stdio.h>
# include <stdbool.h>
# include <string.h>
# include <stdlib.h>
int main ()
{
char * buffer;
buffer = malloc (2);
if (buffer == NULL){
printf("big errors");
}
strcpy(buffer, "hello");
printf("buffer is %s
", buffer);
free(buffer);
return 0;
}
I allocated 2 bytes of memory to the pointer/char buffer
yet if I assign the C-style string hello
to it, it still prints the entire string, without giving me any errors. Why doesn't the compiler give me an error telling me there isn't enough memory allocated? I read a couple of questions that ask how to check how much memory malloc
actually allocates but I didn't find a concrete answer. Shouldn't the free
function have to know exactly how much memory is allocated to buffer
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…