简体   繁体   中英

Is it a memory leak in the following C code?

Is it a memory leak in the flowing C code?

 #include <stdlib.h>
 int *a;

 int main() {
      a = malloc(sizeof(int)*10);
      return 0;
 }

At least the way most people use the term, the answer would be yes--any memory allocated by the program and never freed is considered a leak.

At the same time, most people are concerned primarily with progressive leaks--ones that can/will leak progressively more memory as a program runs, for example from doing an allocation inside a loop, and failing to free that memory.

Especially for something that really needs some memory to remain allocated for the entire life of the program anyway, the difference between freeing before exit and leaving the memory allocated until exit is complete becomes more a question of hair-splitting than a truly useful distinction. Some view it as a travesty to leave the memory allocated, even if it's only freed immediately before exit. Others view it as a waste of code (and invitation to bugs) to explicitly free memory immediately before exit (when any competently designed OS will regain the process' resources anyway).

由于程序一旦分配就退出,那么linux(或windows)会自动free那个内存空间,所以没有泄漏,但你在malloc之后做了一些事情,在程序结束之前就会出现泄漏

This will be reported by valgrind and Intel Inspector as memory leaks as the memory allocated is not freed. However, it may possible that this may not have an impact on the program.

If this allocated memory is required till the exit of the program, then this leak warning can be avoided. But design must specify that not freeing will not lead to other problems like out of memory. For example, there might be some singleton instance of a controller object which must be present as long as program runs.

However, if such allocations are lost and never used and design does not consider them, then it is definitely a leak.

Now, in your case, this allocated memory is used no where. Hence, such allocations must be considered as leaks.

It might possible that OS takes away all the memory when program exits. This must not be taken for granted when application has to run for a long time (like server applications) and will exists for a very long and will have lots of maintenance in the future.

Yes there is a memory leak in your program. You are allocating a memory of size 10*4 [ consider int takes 4 bytes ] and you are not freed the memory. To avoid memory leak you must free the allocated memory.

    #include <stdlib.h>
    int *a;

    int main()
    {
         /* allocating the Memory */
         a = malloc( sizeof (int) *10 );
         /* free the allocate memory */
         free ( a );
         return 0;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM