I was practising my programming and memory allocation.When i execute without valgrind the program works and it does what it needs to do. Then i executed with valgrind to see if i had any memory leaks.This is what i got when executing with valgrind. Im kind of new and i cant find why do i have so many memory leaks or errors. 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.
Also, you might consider to use vector<int>
instead of *k
, *l
, *s
and *t
.
Example:
#include <vector>
using namespace std;
vector<int> s;
s[0]=1;
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.