I'm trying to work on a Dijikstra implementation and this is the graph generation code that I have
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <math.h>
#define MAX 300
int main (int argc, char *argv[]){
int v = atoi(argv[1]);
int SIZE = v*v;
int* adjMatrix = malloc(sizeof(int)* SIZE);
graphGeneration(adjMatrix, v);
free(adjMatrix);
return 0;
}
void graphGeneration(int* adj, int numV){
int i, j, r;
for(i = 0; i< numV; i++){
for(j=0; j < numV; j++){
if(i == j){
adj[i * numV + j] = 0;
}
else{
r = rand() % MAX;
adj[i * numV + j] = r;
adj[j * numV + i] = r;
}
}
}
}
When I try a value of v in 1000's it seems to work fine, but when I try to enter a value of v = 10,000+ I get a segfault (Specifically at 50,000 is the number I noticed). Running valgrind gets me the error in the title at this method. Reposting here for convenience:
Invalid write of size 4
at 0x400800: graphGeneration
by 0x4006E3: main
Address 0x0 is not stack'd, malloc'd or (recently) free'd
Access not within mapped region at address 0x0
Anyone have any ideas for how to debug this or if there are any obvious errors here?
I also noticed this bit in valgrind
Warning: silly arg (-7179869184) to malloc()
which I'm not sure if it's related, but it seems like a strange thing as well.
malloc()
take? Second, what doesmalloc()
return when you get the segfault? – Andrew Henlesizeof(double[v][v])
so you don't have to do the computations manually. Then, check the return ofmalloc
for such large allocations. Third, try your code with small examples, such that you have any chance to debug. – Jens Gustedt