krm - 1 year ago 51
C Question

# How to tell if malloc worked?

I'm wondering how could I know if malloc did it's job?
Is there a way I could check if I'm using malloc properly?
Printing the matrix values addresses will tell me something other than been contiguous?

``````int main (int argc, char ** argv)
{
int x,y;// int variables
char str[100];//char variable

/*Variable pointer to pointer long long int type*/
int ** matrix;//matrix 3X6

/*We alocate memory for the first matrices dimension (rows)*/
matrix= malloc(3 * sizeof(*matrix));

/*We alocate memory for the second matrices dimension (columns)*/
for(x=0; x<6; x++){
matrix[x]=malloc(6 * sizeof(int));

}
/* Matrix initialization*/
for(y=0;y<3;y++){ // row matrix iterations
for(x=0;x<6;x++)//columns matrix iterations
{
matrix[y][x]=x;// assign value
}
}
/*Print each matrix position value*/
sprintf(str, "\nMatrix\n");
write(1, str, strlen(str));
for(int y=0; y<3; y++){
for(int x=0; x<6; x++){
sprintf(str,"[%d][%d]=%d    ", y , x, matrix[y][x]);
write(1, str, strlen(str));
}
sprintf(str, "\n");
write(1, str, strlen(str));
}
exit(0);
}
``````

`malloc` and other dynamic memory allocation functions return a pointer to the memory you allocated when they suceed, or `NULL` if they failed or you called them with a nonsensical value (like doing `malloc(0)` or somesuch).

From the manual page on `malloc`:

[...] On error, these functions return NULL. NULL may also be returned by a successful call to malloc() with a size of zero, or by a successful call to calloc() with nmemb or size equal to zero. [...]

For your code, add a simple check against null to see if your `malloc` succeeded:

``````for(x=0; x<6; x++){
matrix[x]=malloc(6 * sizeof(int));
if (matrix[x] == NULL) {
printf("Dynamic memory allocation failed");
//dostuff
}
}
``````