简体   繁体   English

这个 memory 是从我的程序还是计算机中泄漏的? 我该如何解决?

[英]Is this memory leak from my program or the computer? How can I fix it?

I was practising my programming and memory allocation.When i execute without valgrind the program works and it does what it needs to do.我正在练习我的编程和 memory 分配。当我在没有 valgrind 的情况下执行时,程序可以工作并且它可以完成它需要做的事情。 Then i executed with valgrind to see if i had any memory leaks.This is what i got when executing with valgrind.然后我用 valgrind 执行,看看我是否有任何 memory 泄漏。这是我用 valgrind 执行时得到的。 Im kind of new and i cant find why do i have so many memory leaks or errors.我有点新,我找不到为什么我有这么多 memory 泄漏或错误。 The code is below.代码如下。 Thanks!!谢谢!!

在此处输入图像描述

 1 #include <stdio.h>
  2 #include <stdlib.h>
  3 int* fun(int *l){
  4          int *k;
  5          k = (int *)malloc (4*sizeof(int));
  6          for(int i = 0; i<4; i++){
  7              k[i] = 2*l[i];
  8              l[i] += 1;
  9          }
 10          return k;
 11          free(k);
 11 }
 12 int main(){
 13          int *s;
 14          int *t;
 15          s = (int *)malloc (4*sizeof(int));
 16          s[0] = 2; s[1] = -3; s[2] = 5; s[3] = 0;
 17          t = fun(s);
 18          for(int i = 0; i<4; i++){
 19              printf(" %d   %d\n", s[i], t[i]);
 20          }
 21          free(s);
 22          free(t);
 23          return 0;
 24 }

The free statement in your function fun is never executed because of the return statement just before it. function fun中的free语句永远不会执行,因为它之前的return语句。

Also, you might consider to use vector<int> instead of *k , *l , *s and *t .此外,您可以考虑使用vector<int>代替*k*l*s*t

Example:例子:

#include <vector>
using namespace std;

vector<int> s;      
s[0]=1; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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