The folowing function code:
void add_edge(int** point, int start, int end)
{
int x;
//start->end edge
x=point[start][0];
if(x>=2)
{
int* temp=new int[x+1];
for(int i=0; i<=x; i++)
temp[i]=point[start][i];
// delete[] point[start];
point[start]=temp;
}
point[start][++point[start][0]]=end;
if(start==end) return;
//end->start edge
x=point[end][0];
if(x>=2)
{
int* temp=new int[x+1];
for(int i=0; i<=x; i++)
temp[i]=point[end][i];
// delete[] point[end];
point[end]=temp;
}
point[end][++point[end][0]]=start;
}
has a memory allocation error which I cannot find.
From valgrind I get this:
==9253== Invalid write of size 4
==9253== at 0x8048643: add_edge(int**, int, int) (c1.cpp:34) (line: point[start][++point[start][0]]=end;)
==9253== by 0x8048C8B: main (c1.cpp:184) (line: add_edge(point,start,end); )
==9253== Address 0x2d6a7074 is 0 bytes after a block of size 12 alloc'd
==9253== at 0x4025FE5: operator new[](unsigned int) (vg_replace_malloc.c:299)
==9253== by 0x80485D0: add_edge(int**, int, int) (c1.cpp:28)
==9253== by 0x8048C8B: main (c1.cpp:184)
==9253==
==9253== Invalid write of size 4
==9253== at 0x80486EA: add_edge(int**, int, int) (c1.cpp:48) (line: point[end][++point[end][0]]=start; )
==9253== by 0x8048C8B: main (c1.cpp:184)
==9253== Address 0x2d6a7134 is 0 bytes after a block of size 12 alloc'd
==9253== at 0x4025FE5: operator new[](unsigned int) (vg_replace_malloc.c:299)
==9253== by 0x8048677: add_edge(int**, int, int) (c1.cpp:42)
==9253== by 0x8048C8B: main (c1.cpp:184)
==9253==
--9253-- REDIR: 0x41e07c0 (__GI_strlen) redirected to 0x4026ccc (__GI_strlen)
If I understand your uncommented code correctly, the first element of each subarray describes the number of following elements. It also looks like you are trying to grow the subarray by one element. If that is the case you need
new int[x+2](1 for growth, and 1 for the length field).However, please find a cleaner way to write your code;
point[start][++point[start][0]]is grotesque!