I am writing a mex code and I am thinking that I am not using memory very efficiently. Here is what I do. I am allocating memory for variable called out like
out=mxMalloc(sizeof(double)*N);
plhs[0]=mxCreateDoubleMatrix(1,N,mxREAL);
set(plhs[0],out);
The problem is that I am not freeing memory that I allocate for variable out because if I do I will receive segmentation error since I will use it in Matlab. So can anyone suggest me a better technique to do what above commands are doing ? Is there anyway to free memory for out or to avoid defining matrix of length 1X N?
Thanks.
You don't need to allocate the array with mxMalloc. mxCreateDoubleMatrix already allocates the array. Once you have your pointer to this data (obtained using mxGetPr), you can then fill the array with the necessary values.
double *out;
// Allocate memory for the first output
plhs[0] = mxCreateDoubleMatrix(1,N,mxREAL);
// Get the pointer to the output data
out = mxGetPr(plhs[0]);
// Run your algorithm here to populate out with the data you need
If for some reason you do need to create out in some other way, you want to copy the contents of that separate array into the output prior to freeing the memory.
double *out;
double *realout;
// Allocate data to use internally
out = mxMalloc(sizeof(double) * N);
// Initialize the array that will be returned to MATLAB
plhs[0] = mxCreateDoubleMatrix(1, N, mxREAL);
realout = mxGetPr(plhs[0]);
// Now copy all values to the MATLAB output
for ( j = 0; j < N; j++ )
realout[j] = out[j];
// Now you can free up memory for out
mxFree(out)
Related
I need to initialize a 2D array in C after dynamically allocating memory for it. I'm allocating memory as follows:
double **transition_mat = (double **) malloc(SPACE_SIZE * sizeof(double *));
for (int i = 0; i < SPACE_SIZE; i++) {
transition_mat[i] = (double *) malloc(SPACE_SIZE * sizeof(double));
}
but then I want to initialize it to a certain 2D array, similar to the way initialization can be done when storing the array on the stack:
double arr[2][2] = {{1.0, 7.0}, {4.1, 2.9}};
However, after allocating memory in the first code segment, trying to do assignment as follows produces an error:
transition_mat = (double **) {{1.0, 7.0}, {4.1, 2.9}};
Does anyone know of a clean way to initialize arrays after malloc'ing memory?
Note: someone suggested that I loop over 0 <= i < SPACE_SIZE and 0 <= j < SPACE_SIZE and assign values that way. The problem with that is that the entries cannot simply be computed from i and j, so that code ends up looking no cleaner than any brute force method.
If you're going to have all the data as literals in the code (to do the initialization), why not just store that as an explicit 2D array to begin with, and be done?
Worst case, do the dynamic allocation and copy from your existing array.
Make it static const inside the function, or at global scope, depending on the access pattern you need.
I have fullNames, which is a 2D array that has sorted full names in it and I want to copy its content into sortedNames, which is a 2D array that exists out side of this function. (I get ***sortedNames as a parameter).
I dynamically allocated this array, but the copying does not succeed. The program crashes after the 4th attempt to copy a name from fullNames to sortedNames. Why?
stringcpy and stringlen are functions that I created. They do the same thing as strcpy and strlen does.
/*allocating memory for sortedNames*/
*sortedNames = (char**) malloc(n);/*n is the number of names*/
/*allocating memory for each sortedNames array*/
for (i = 0; i < n; i++)
{
(*sortedNames)[i] = (char*) malloc(stringlen(fullNames[i])+1);
}
/*Copying fullNames into sortedNames*/
for (i = 0; i < n; i++)
{
stringcpy((*sortedNames)[i],fullNames[i]);
}
You do not allocate enough memory for the array of pointers, you should allocate this way:
*sortedNames = (char**)malloc(n * sizeof(char *));
Furthermore, why not use strlen and strcpy in place of stringlen and stringcpy? It this just a typo or do these function perform some extra function?
Regarding the cast on malloc return value, you could remove it if you do not intend to compile your code as C++ and write this:
*sortedNames = malloc(n * sizeof(**sortedNames));
Regarding the extra parentheses around **sortedNames, be aware that they are not necessary so you can remove them or not depending on your local style conventions.
There should be 2 edits as the memory allocated may not be sufficient. This code :
(*sortedNames)[i] = (char*) malloc(n);
allocates memory for n bytes whiles you need memory for (n*the size of string) bytes.The second malloc may work as char occupies 1 byte. But try to use sizeof() to make it system independent.
The correct code would be :
(*sortedNames)[i] = malloc(n*sizeof(char *));
I am using GTK, and I am not sure with malloc() function here. Valgrind gives me a memory leak, what I am doing bad?
at first I create pointer to pointer to pointer to GTK widget, because I need three dimensional array.
GtkWidget*** widgets;
and I am using malloc like this:
widgets = malloc((1)*sizeof(GtkWidget**));
for(i = 0; i<= l-1; i++) // l = 4 in my case
{
widgets[i] = malloc((1)*sizeof(GtkWidget*));
for(j = 0; j<=3; j++) // 4 is number of elements in this dimension
{
widgets[i][j] = malloc((1)*sizeof(GtkWidget));
}
}
and at the end I am doing this:
widgets[0][0] = gtk_menu_item_new_with_label("MyLabel");
gtk_menu_shell_append(GTK_MENU_SHELL(indicator_menu), widgets[0][0]);
my array can be smaller and bigger, so I am using dynamic allocation of array, my maximal array indexes are something like widgets[3][3].
I did not post whole code, because it is pretty long, I sent here just the parts for which was valgrind complaining to. What I am doing bad? thank you.
You're only allocating the size of a pointer, when you mean to allocate an array of pointers.
// this will allocate a single character pointer
char ** ptr = malloc(1 * sizeof(char *));
// this will allocate n character pointers
char ** ptr = malloc(n * sizeof(char *));
So if you want a two dimensional array of dimension NxM, you'll need to allocate an array of size N, then walk through that array from 0 to N-1 and allocate arrays of size M.
What you're doing now is assigning pointers returned from malloc to memory you don't own. Is what you actually want a two-dimensional array of pointers to GtkWidget structures?
Using l as a local variable is not a good idea. It is very easy to make a mistake between l and 1, in some editors they look very much the same.
widgets = malloc((l)*sizeof(GtkWidget**)); //is what you needed
iso
widgets = malloc((1)*sizeof(GtkWidget**));
Over here with syntax highlighting the problem immediately appears.
So another suggestion is to for sure use an editor with syntax highlighting
I've got 2 processes (Client and Server) that are communicating through shared memory.
I need to create a 2D Array that is Dynamic (based on parameters). The array is stored in a struct and then written to the shared segment.
I can write the array to the shared memory, but cannot retrieve it from the other process.
Client Code:
struct shared_use_st {
int written_by_you;
int **PID_PRI_array;
};
/* Prepare Dynamic 2D array */
data_store = malloc(/*ROWS*/ 5 * sizeof(int*));
for(i=0;i<5; i++)
data_store[i] = malloc(/*COLS*/ 2 * sizeof(int));
/* Prepare Dynamic 2D array - Shared Memory Seg */
shared_stuff->PID_PRI_array = malloc(/*ROWS*/ 5 * sizeof(int*));
for(i=0;i<5; i++)
shared_stuff->PID_PRI_array[i] = malloc(/*COLS*/ 2 * sizeof(int));
/* Write PID and PRI to data_store array */
data_store[0][0] = pid;
data_store[0][1] = 1;
data_store[1][0] = 12345;
data_store[1][1] = 2;
data_store[2][0] = 12346;
data_store[2][1] = 3;
data_store[3][0] = 12347;
data_store[3][1] = 4;
data_store[4][0] = 12348;
data_store[4][1] = 5;
for(i=0;i<5;i++){
for(x=0;x<=1;x++){
shared_stuff->PID_PRI_array[i][x] = data_store[i][x];
}
}
Server Code:
for(i=0;i<5;i++){
printf("PID: %d, PRI:%d\n", shared_stuff->PID_PRI_array[i][0], shared_stuff->PID_PRI_array[i][1]);
}
I get a "Segmentation Fault" error.
Thanks.
Even if your shared_stuff object is in shared memory, you are not writing the array to shared memory. You are allocating space with malloc, writing data to that space, and then putting pointers to that space into shared_stuff. malloc allocates space within the current process‘ normal address space, not in a shared memory segment you have created. You need to write the array contents to the shared memory.
Presuming there is enough space for the array within the shared memory segment, you will have to manage the addresses yourself, not using malloc. (If there is not enough space, you must make the shared memory segment larger or convey the information in pieces over time.)
You can place a variable-length array within the shared memory segment as follows.
First, define a structure that contains all the “management” information you need, such as the array sizes:
struct StuffStruct
{
size_t NumberOfRows, NumberOfColumns;
… Other information as desired.
};
Create a pointer to that structure and set it to point to the shared memory segment:
struct StuffStruct *Stuff = shm; // shm contains the address from shmat, performed previously.
Create a pointer to an array with the desired number of columns and set it to point into the shared memory segment after the initial structure:
int (*data_store)[NumberOfColumns] = (int (*)[NumberOfColumns]) ((char *) Stuff + sizeof *Stuff);
(Note for C purists: Yes, the C standard does not guarantee what happens when you do pointer arithmetic like this. However, any implementation providing shared memory support must provide support for this sort of pointer arithmetic.)
Note that sizeof *Stuff + NumberOfRows * NumberOfColumns * size(int) must be no greater than the size of the shared memory segment. Otherwise you will overrun the shared memory segment in the next step.
For the next step, fill the array with data: Assign values to the elements of data_store as for a normal two-dimensional array.
In the server, set Stuff the same way. Then, after the client has written the shared memory segment, read the numbers of rows and columns from Stuff. Then set data_store the same way. Then read from data_store.
i have a 2D array of size 5428x5428 size.and it is a symmetric array. but while compiling it gives me an error saying that array size too large. can anyone provide me a way?
This array is to large for program stack memory - thats your error.
int main()
{
double arr[5428][5428]; // 8bytes*5428*5428 = 224MB
// ...
// use arr[y][x]
// ...
// no memory freeing needed
}
Use dynamic array allocation:
int main()
{
int i;
double ** arr;
arr = (double**)malloc(sizeof(double*)*5428);
for (i = 0; i < 5428; i++)
arr[i] = (double*)malloc(sizeof(double)*5428);
// ...
// use arr[y][x]
// ...
for (i = 0; i < 5428; i++)
free(arr[i]);
free(arr);
}
Or allocate plain array of size MxN and use ptr[y*width+x]
int main()
{
double * arr;
arr = (double*)malloc(sizeof(double)*5428*5428);
// ...
// use arr[y*5428 + x]
// ...
free(arr);
}
Or use combined method:
int main()
{
int i;
double * arr[5428]; // sizeof(double*)*5428 = 20Kb of stack for x86
for(i = 0; i < 5428; i++)
arr[i] = (double)malloc(sizeof(double)*5428);
// ...
// use arr[y][x]
// ...
for(i = 0; i < 5428; i++)
free(arr[i]);
}
When arrays get large, there are a number of solutions. The one that is good for you depends heavily on what you are actually doing.
I'll list a few to get you thinking:
Buy more memory.
Move your array from the stack to the heap.
The stack has tighter size limitations than the heap.
Simulate portions of the array (you say yours is symmetric, so just under 1/2 of the data is redundant).
In your case, the array is symmetric, so instead of using an array, use a "simulated array"
int getArray(array, col, row);
void setArray(array, col, row, value);
where array is a data structure tha only holds the lower left half and the diagonal. The getArray(..) then determines if the column is greater than the row, and if it is, it returns (note the reversed entries getArray(array, row, col); This leverages the symmetric property of the array without the need to actually hold both symmetric sides.
Simulate the array using a list (or tree or hash table) of "only the value holding items"
This works very well for sparse arrays, as you no longer need to allocate memory to hold large numbers of zero (or empty) values. In the event that someone "looks up" a non-set value, your code "discovers" no value set for that entry, and then returns the "zero" or empty value without it actually being stored in your array.
Again without more details, it is hard to know what kind of solution is the best approach.
When you create local variables, they go on the stack, which is of limited size. You're blowing through that limit.
You want your array to go on the heap, which is all the virtual memory your system has, i.e. gigs and gigs on a modern system. There are two ways to manage that. One is to dynamically allocate the array as in k06a's answer; use malloc() or your platform-specific allocator function (e.g. GlobalAlloc() on Windows) . The second is to declare the array as a global or module static variable, outside of any function.
Using a global or static has the disadvantage that this memory will be allocated for the entire lifetime of your program. Also, pretty much everybody hates globals on principle. On the other hand, you can use the two-dimensional array syntax, "array[x][y]" and the like, to access array elements... easier than doing array[x + y * width], plus you don't have to remember whether you're supposed to be doing "x + y * width" or "x * height + y" .