Allocate a matrix in C using malloc - c

I wrote a C code that usea a matrix of double:
double y[LENGTH][4];
whith LENGTH=200000 I have no problem.
I have to increase the numbers of rows to LENGTH=1000000 but when I enter this value and execute the program it returns me segmentation fault.
I tried to allocate more memory using malloc:
double **y = (double **)malloc(LENGTH * sizeof(double*));
for(int i = 0; i < LENGTH; i++){
y[i] = (double *)malloc(4 * sizeof(double));
}
I run the the code above and after some second of calculations it still gives me "segmentation fault".
Could anyone help me?

If you want a dynamic allocated 2D array of the specified row-width, just do this:
double (*y)[4] = malloc(LENGTH * sizeof(*y));
There is no need to malloc each row in the matrix. A single malloc and free will suffice. Only if you need dynamic row width (each row can vary in width independent of others) or the column count is arbitrary should a nested malloc loop be considered. Neither appears to be your case here.
Notes:
Don't cast malloc in C programs
Be sure to free(y); when finished with this little tryst.

The reason your statically allocated array is segfaulting with a million elements is (presumably) because it's being allocated on the stack. To have your program have a larger stack, pass appropriate switches to your compiler.
ProTip: You will experience less memory fragmentation and better performance if you flip your loop around, allocating
(double *)malloc(LENGTH * sizeof(double));
four times. This will require changing the order of your indices.
I ran the the code with this definition and after some second of calculations it still gives me "segmentatin fault"
If you're getting a segmentation fault after allocating the memory, you're writing outside of your memory bounds.

I run this code
#include <stdio.h>
#include <stdlib.h>
// We return the pointer
int **get(int N, int M) /* Allocate the array */
{
/* Check if allocation succeeded. (check for NULL pointer) */
int i, **table;
table = malloc(N*sizeof(int *));
for(i = 0 ; i < N ; i++)
table[i] = malloc( M*sizeof(int) );
return table;
}
void free2Darray(int** p, int N) {
int i;
for(i = 0 ; i < N ; i++)
free(p[i]);
free(p);
}
int main(void)
{
const int LENGTH = 1000000;
int **p;
p = get(LENGTH, 4);
printf("ok\n");
free2Darray(p ,LENGTH);
printf("exiting ok\n");
return 0;
}
and it was executed normally.
I got the code from my pseudo-site.
You should not cast what malloc returns. Why?
Also notice, that since you need a dynamic allocation only for the number of rows, since you know the number of columns. So, you can modify the code yourself (so that you have some fun too. :) )
I hope you didn't forget to **free** your memory.

Related

Where to free memory, while creating 2d array? valgrind error

I am starting to learn dynamic memory allocation. In this code, I have created in main function 2d array:
int r, c;
scanf("%d %d\n", &r, &c);
size_t row = (size_t) r;
size_t col = (size_t) c;
int **board = malloc(row * sizeof(*board));
for (int i = 0; i < r; i++) {
board[i] = malloc(col * sizeof(*board[i]));
}
(I need both int and size_t because of for loops, especially when r>=0, which is always true for size_t).
Then I change the board with other functions. Valgrind returs:
==59075== 364 (56 direct, 308 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==59075== at 0x483577F: malloc (vg_replace_malloc.c:299)
==59075== by 0x10B4DB: main (name22.c:122)
==59075==
122 line is:
int **board = malloc(row*sizeof( *board));
I suppose I have to use free(), but after checking other answers I don't know, where is my mistake and where to put free(), if use use this table through the rest of the program. I would appreciate your hints and explanations.
`
When you call int **board = malloc(row * sizeof(*board)); , the system will allocate you row * sizeof(*board) bytes of memory and then return a pointer to the start of that memory (ie - a memory address), which you are storing in the int ** variable called board.
When your program finishes, the system will reclaim that memory, so if your program is short lived, it probably doesn't matter very much, but it's good practise to get into the habit of freeing your memory because it will not reclaim any memory at all until your program exits, unless you tell it to.
For that reason, you should always call free(...), passing in the memory address you were given when you first called malloc(...), once you are done with that memory. In most cases, each call to malloc(...) should have an equal and opposite call to free(...)
This is important because your system has a finite amount of memory. If your program is asking for resources and then never giving them back when they are done you will eventually run out of memory - this is what is called a "memory leak".
So for you, calling free(...) correctly, is going to look something like this:
int **board = malloc(row * sizeof(*board));
for (int i = 0; i < r; i++) {
board[i] = malloc(col * sizeof(*board[i]));
}
// Do something with board
for (int i = 0; i < r; i++) {
free(board[i]);
}
free(board);

Using realloc to double an arrays size during runtime. Is my code correct?

I am unsure if I am using the realloc function correctly.
In my program, I first ask the user for the size of the array and allocate memory for it using malloc, then initialise it with some values.
Then I want to make the same array twice it's size, using realloc. Here is my code. Am I using realloc to resize int *A correctly?
#include <stdio.h>
#include <stdlib.h>
int main(){
int n;
printf("Enter size of array\n");
scanf("%d", &n);
int *A = (int*)malloc(n*sizeof(int)); //dynamically allocated array
for (int i = 0; i < n; i++) //assign values to allocated memory
{
A[i] = i + 1;
}
A = (int*)realloc(A, 2*sizeof(int)); //make the array twice the size
free(A);
}
When using malloc() , don't cast the return value as said here
You are not using the right size. In hereint *A = (int*)malloc(n*sizeof(int)); the size given to malloc is n*sizeof(int). If you want twice that size, you should call realloc() with n*sizeof(int)*2 instead of 2*sizeof(int)
Handle realloc() failure. In case realloc(A, new_size) fails, A == NULL and you will have memory leak. So, use a different pointer B, check if (B != NULL) and then assign A = B (old_size = new_size). If B == NULL deal with the allocation fail
In this case it's easier to double the n before malloc so you don't have the use realloc, because you know, that you gonna double the arraysize. Using realloc can slow the working of the program, because if you make it longer, and the adresses after the currently allocated memories aren't free, then the whole array will be moved. Also you have the change the last line as it was suggested before me.

C: free() for row of 2d int array makes program halt

I am relatively new to C and have coded (or more precise: copied from here and adapted) the functions below. The first one takes a numpy array and converts it to a C int array:
int **pymatrix_to_CarrayptrsInt(PyArrayObject *arrayin) {
int **result, *array, *tmpResult;
int i, n, m, j;
n = arrayin->dimensions[0];
m = arrayin->dimensions[1];
result = ptrvectorInt(n, m);
array = (int *) arrayin->data; /* pointer to arrayin data as int */
for (i = 0; i < n; i++) {
result[i] = &array[i * m];
}
return result;
}
The second one is used within the first one to allocate the necessary memory of the row vectors:
int **ptrvectorInt(long dim1, long dim2) {
int **result, i;
result = malloc(dim1 * sizeof(int*));
for (i = 0; i < dim1; i++) {
if (!(result[i] = malloc(dim2 * sizeof(int)))){
printf("In **ptrvectorInt. Allocation of memory for int array failed.");
exit(0);
}
}
return result;
}
Up to this point everything works quite fine. Now I want to free the memory occupied by the C array. I have found multiple threads about how to do it, e.g. Allocate and free 2D array in C using void, C: Correctly freeing memory of a multi-dimensional array, or how to free c 2d array. Inspired by the respective answers I wrote my freeing function:
void free_CarrayptrsInt(int **ptr, int i) {
for (i -= 1; i >= 0; i--) {
free(ptr[i]);
}
free(ptr);
}
Nontheless, I found out that already the first call of free fails - no matter whether I let the for loop go down or up.
I looked for explenations for failing free commands: Can a call to free() in C ever fail? and free up on malloc fails. This suggests, that there may have been a problem already at the memory allocation. However, my program works completely as expected - except memory freeing. Printing the regarded array shows that everything should be fine. What could be the issue? And even more important: How can I properly free the array?
I work on a Win8 64 bit machine with Visual Studio 10 64bit compiler. I use C together with python 3.4 64bit.
Thanks for all help!
pymatrix_to_CarrayptrsInt() calls ptrvectorInt() and this allocation is made
if (!(result[i] = malloc(dim2 * sizeof(int)))){
then pymatrix_to_CarrayptrsInt() writes over that allocation with this assignment
result[i] = &array[i * m];
causing a memory leak. If array is free()'d then attempting to free() result will fail

In C, memory allocating fails, why?

int x;
int komsuSayisi;//adjanceny matrix
int **arkadas;
int t;
int komsu[24][24];
scanf("%d",&t);
**arkadas = (int **)malloc( t*sizeof( int* )); //allocating rows
for(i=0; i<t; i++)
{
x=0;
arkadas[i] = (int *)malloc( t*sizeof(int) ); //allocating cow temporarily
for(j=0; j<t; j++)
{
komsu[i][j]=fark(kelime[i],kelime[j]); //fark returns 1 or 0.
//so i put those 1 ones to another matrix,arkadas
if(komsu[i][j]==1){
komsuSayisi++;
arkadas[i][x]=j;
x++;
}
arkadas[i] = (int *) realloc(arkadas[i], x);
//real allocating here
}
It gives error and shut downs.There is nothing wrong. What i want is adjanceny is too big to search so i will easily search the "1" ones with this matrix.
**arkadas = (int **)malloc( t*sizeof( int* ));
should be
arkadas = malloc( t*sizeof( int* ));
**arkadas dereferences an uninitialised pointer, resulting in you trying to write to an unpredictable address. You don't own the memory at this address so it isn't safe to try and write to it.
The second form assigns the address of an array of pointers to the local variable arkadas; this is what need to do.
Later in your program
if(komsu[i][j]==1){
komsuSayisi++;
arkadas[i][x]=j;
x++;
}
arkadas[i] = (int *) realloc(arkadas[i], x);
code inside the if condition attempts to write to arkadas[i] before you allocate it. This also invokes undefined behaviour and will likely crash. You can avoid the crash by removing the line arkadas[i][x]=j; and swapping your realloc call for malloc (you need the address of a previous allocation before you can call realloc)
if(komsu[i][j]==1){
komsuSayisi++;
x++;
}
arkadas[i] = malloc(x*sizeof(int));
I see
komsuSayisi++;
You didn't paste the whole code but probably thats what is crashing your program... I don't see any initializing previous to that increment....
this plus the deferentiation posted on the other answer

Could not allocate memory

In my C code I am allocating memory for 2d array double E[2000][2000]; but when I run it gets a runtime error Segmentation fault(core dumped) and when I reduce the array size to somewhere around 900 then the code runs fine.
Why it is showing runtime error since double take 64 bits memory (IEEE standard) so the code should take approximately 32MB which is not much compared to the ram size.And if it is not supported in C then how should I proceed if my maximum number of data that I have to store is 4000000 each are floating point numbers.
Are you declaring E as a local variable ? If so, you're running out of stack memory.
void func()
{
double E[2000][2000]; /// definitely an overflow
}
Use dynamic allocation:
double* E = malloc(2000 * 2000 * sizeof(double));
/// don't forget to "free(E);" later
Or if you need the 2D array, use a zig-zag:
double** E = malloc(2000 * sizeof(double*));
/* check that the memory is allocated */
if(!E)
{
/* do something like exit(some_error_code); to terminate your program*/
}
for(i = 0 ; i < 2000 ; i)
{
E[i] = malloc(2000 * sizeof(double));
/* check that the memory for this row is allocated */
if(!E[i])
{
/* do something like exit(some_error_code); to terminate your program*/
}
}
Then the deallocation is a little more complicated:
for(i = 0 ; i < 2000 ; i)
{
free(E[i]);
}
free(E);
P.S. If you want to keep all of you data in a continuous way, there's a trick (code from Takuya Ooura's FFT Package)
double **alloc_2d(int n1, int n2)
{
double **ii, *i;
int j;
/* pointers to rows */
ii = (double **) malloc(sizeof(double *) * n1);
/* some error checking */
alloc_error_check(ii);
/* one big memory block */
i = (double *) malloc(sizeof(double) * n1 * n2);
/* some error checking */
alloc_error_check(i);
ii[0] = i;
for (j = 1; j < n1; j++) {
ii[j] = ii[j - 1] + n2;
}
return ii;
}
void free_2d(double **ii)
{
free(ii[0]);
free(ii);
}
The you just call
double** E = alloc2d(2000, 2000);
and
free_2d(E);
I assume you are allocating it on the stack by simply
double E[2000][2000];
which will probably be more than stack size allocated to your program.
Try using malloc (or new in c++) or increase the default stack size of your program using options. gcc can be configured using setrlimit() for this purpose.
setting stack size in gcc
Keep in mind that even if stack size is increased, an array of this size should be global
You can also use a single statement to allocate a 2D array on heap if one dimension is fixed in size
double (* E)[COLUMN_SIZE];
int rows = 20; // this is dynamic and can be input from user at run time
E = malloc(rows * sizeof(*E)); // this needs to be freed latter
A more detailed similar example
allocating 2d array without loops
It depends on where you allocate the array. Using stack space will probably cause an overflow (unless you get the linker to allocate an extra large stack).
For example, this might not work
int main()
{
double E[2000][2000]; // Likely an overflow
}
However, moving the array to the static memory area
double E[2000][2000];
int main()
{
// use E here
}
will probably avoid the problem.

Resources