Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valgrind: Address 0x0 is not stack'd, malloc'd or (recently) free'd for larger input values only

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.

like image 258
Brain Meme Avatar asked Dec 01 '25 23:12

Brain Meme


1 Answers

Have a look at some malloc() manual: Its argument is of type size_t for a reason. int is not guaranteed to hold any possible object size, size_t is. And it is unsigned btw -- negative sizes don't make much sense.

So just write

size_t SIZE = ((size_t)v) * v;

as your v is an int you have to force this multiplication to be done as size_t by casting one of the arguments.

A slightly better way would be to make v an unsigned long and use strtoul() instead of atoi().


Then, check the result of your malloc() before you use it. It might still return NULL, even with a correct size argument. If it does, this simply means you don't have enough RAM available at that moment.

After all, with v=10000 and assuming an int takes four bytes (which is very common), you already attempt to allocate 400 MB at once.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!