P
P
polak2282021-09-05 15:26:56
C++ / C#
polak228, 2021-09-05 15:26:56

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; 
}

Why does the code above run without errors when malloc() didn't allocate enough memory?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2021-09-05
@polak228

Because C doesn't control the program's memory usage. Any control on the conscience of the developer.

W
Wataru, 2021-09-05
@wataru

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 question

Ask a Question

731 491 924 answers to any question