Skip to content

Commit 48f03b2

Browse files
fix: memory leak in bellman_ford
1 parent bddae75 commit 48f03b2

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

dynamic_programming/bellman_ford.cpp

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#include <limits.h>
2+
23
#include <iostream>
4+
#include <vector>
35

46
using namespace std;
57

@@ -13,13 +15,13 @@ class Edge {
1315
class Graph {
1416
public:
1517
int vertexNum, edgeNum;
16-
Edge *edges;
18+
std::vector<Edge> edges;
1719

1820
// Constructs a graph with V vertices and E edges
1921
Graph(int V, int E) {
2022
this->vertexNum = V;
2123
this->edgeNum = E;
22-
this->edges = (Edge *)malloc(E * sizeof(Edge));
24+
this->edges.reserve(E);
2325
}
2426

2527
// Adds the given edge to the graph
@@ -36,7 +38,7 @@ class Graph {
3638
};
3739

3840
// Utility function to print distances
39-
void print(int dist[], int V) {
41+
void print(const std::vector<int>& dist, int V) {
4042
cout << "\nVertex Distance" << endl;
4143
for (int i = 0; i < V; i++) {
4244
if (dist[i] != INT_MAX)
@@ -52,7 +54,8 @@ void print(int dist[], int V) {
5254
void BellmanFord(Graph graph, int src) {
5355
int V = graph.vertexNum;
5456
int E = graph.edgeNum;
55-
int dist[V];
57+
std::vector<int> dist;
58+
dist.reserve(E);
5659

5760
// Initialize distances array as INF for all except source
5861
// Intialize source as zero

0 commit comments

Comments
 (0)