Answer the question
In order to leave comments, you need to log in
Why might a program use more dynamic memory than malloc() allocated?
#include <stdlib.h>
int main(int argc, char *argv[1]) {
char *greeting = "Hello, ";
char *name = "User!";
char *result = (char *)malloc(1);
strcat(result, greeting); strcat(result, name);
printf("%s\n", result);
return 0;
}
Answer the question
In order to leave comments, you need to log in
Because C doesn't control the program's memory usage. Any control on the conscience of the developer.
You are not climbing into your memory. The program may crash, you may override the value of some of your other variables.
In your case, you are in luck. Apparently, on your particular computer, your particular operating system at this particular point in time gives you 1 byte, which lies inside the memory page allocated to your application, and there are no further variables of yours there. It doesn't have to happen like that. You run your program at a different time, add more variables or memory allocations, or copy a slightly longer string, and the program can easily crash.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question