C :: Free Memory From A Dynamically Allocated Array Of Pointers To Linked Lists
Feb 26, 2013
Having some frustrating issues trying to free memory from a dynamically allocated array of pointers to linked lists. I think the problem is in how I initialize the pointers to NULL. Is there a more elegant way to have the program recognize that the list is empty so it knows to create a head node for the linked list in the function 'add_end_stub_to_array'?
I ran the code through Valgrind and it says that memory is definitely lost from this array.
This is the structure definition.
Code: struct stub_edge {
int loc_id;
int anim_type;
int mkt;
struct stub_edge *next_node;
};
Here is the code snippet from main allocating and deallocating memory to the array.
Here the function for adding nodes to the lists by reading through a dynamically allocated 2D array. (The end_stubs array is ordered by month and each linked list represents events occuring within the month).
Code:
struct stub_edge **add_end_stub_to_array(int **end_stubs, struct stub_edge **list)
{
long int i = 0;
int mon = 0;
struct stub_edge *current_node1;
struct stub_edge *new_node1;
int break1 = 0;
while(i < num_edges && break1 == 0 && mon < 12)
[Code]...
Here is the function for freeing memory from the list.
I am trying to store each value of a column from a text file into an dynamically allocated array, which needs to be globally declared for further usage in the program.The input textfile contains the following:
#include<stdio.h> #include<stdlib.h> #include<string.h> int main() }
[code]....
The commented printf line gives the entire values of the column, which proves that the file is correctly being read.But on compiling this program I get both compiler warnings and finally segmentation fault.
I'm trying to free allocated memory for structure. It seems like free() gets only pointer and not regular types . my question is basic and simple – is passing pointer to free() frees the pointer or the variable it points at? or both?
I'm trying extremely hard to understand pointers and I have the basic concept down.. I feel as though my knowledge of dynamically allocated pointers and pointers in general is not enough to understand the logic behind what I'm trying to do. The problem is that the donations array must be able to accept any number of donations. I've made it do just that, but there is also an array of pointers which must each point to the same element in the donations array. The program works if I assign int *arrPtr[100] for example, but it does not work if I try to dynamically allocate it to accept the same number of elements for donations entered by the user. Here it's the snippet
#include <iostream> using namespace std; //Function Prototypes
I am having some trouble getting a 3d array of pointers to link up with a linked list for each of the array elements. the 3d array of pointers is declared like this:
Code:
struct particle *cell[MAXCELLS][MAXCELLS][MAXCELLS]; and there are linked lists declared like this: Code: struct particle { /* structure for particles */ double sw[3]; /* square well components */ double hs[3]; /* hard sphere components */ double u[3]; /* unit vector for rotations */ struct particle *link; };
I want to get the array pointers 'cell[x][y][z]' to point to the first observed particle in a function next to main, something like this:
Code:
void generate_list(){ int i,j,k,l; /* determine the number of cells to decompose the simulation box in each of x, y and z directions*/ int(cells_x) = floor(boxX/cell_size); int(cells_y) = floor(boxY/cell_size); int(cells_z) = floor(boxZ/cell_size); /* initialise the array of pointers to NULL */ for (j=0;j<cells_x;j++){
[Code]...
I am getting a pointer type cast error when I compile "assignment from incompatible pointer type",
I am studying/writing/ code for a future Advanced Data Structure class in C++; however I am not suppose to use STL, Templates and etc (the way I just code "kinda" of resembles what I have to use).
My application is suppose to read/analyze all integers contained in a text file of 5-digit integers (10000 - 99999).
For simplicity I am using the following input (or check the attached):
So far, my code is not displaying/printing the lists separated by the first digit of these 5-digits integers. I am expecting it to display/print logically/similar to the following:
Output:
Results for input file numbers.txt: 27 total integers read from file
The 3 unique integers beginning with digit 1 were 18399 17342 19948
The 6 unique integers beginning with digit 3 were 39485 34710 31298 38221 35893 32791
The 4 unique integers beginning with digit 4 were 43928 49238 45678 43210
The 6 unique integers beginning with digit 6 were 64545 62987 66221 61777 66666 65432
The 2 unique integers beginning with digit 8 were 88888 86861
The 1 unique integer beginning with digit 9 was 98765
There were 22 unique 5-digit integers in the file.
The highest unique count in one list was 6 integers.
My code that will follow soon displays/prints only the LAST 5-digits "group" of integers (in this case the 5-digits starting with 3). I am not sure what's wrong with my code; perhaps I am not designing it correctly. May be my calls in it are on the wrong place or I have to write all integers and then traverse it and output it (if that's the case, I am not sure how).
My code follows:
#include <iostream> #include <fstream> #include <iomanip> using namespace std; const int MAX_CELLS = 10; const int UNIQUE_FIVE_DIGIT = 5;
I am having issues freeing memory that I allocated when adding a node to a doubly linked list. I have tried adding free() at the end of the remove function from the list with no luck. I have tried using all sorts of temporary nodes and dummy nodes to free without losing node information. Have tried storing current node, moving to next one, then freeing the old current one, without luck. Everytime I try to free a node it destroys the list. It loses important node information and can no longer operate properly and I am met with all sorts of memory crashes. I will post my add and delete nodes functions here:
/** * Adds a node to a given list * * @param q pointer a a list * @param node pointer to the node to be added */ void list_add(list *q, path *node){ path *pn; if(!(pn = (path*)malloc(sizeof(*pn)))){ perror("malloc"); exit(1);
[Code] ....
Those free's at the end are to get rid of nodes I malloced in find_path. This find_path works really well when run once lol. It finds shortest path and prints it no problem, but doing it over and over again will be problematic as it is leaking almost every bit of memory it uses />.
So in short, how to free an allocated node when I remove it from a list while still being able to use it? I have tried moving the remove function to different locations like the end of the file and still no luck. I even tried allocating a new current_node each iteration of while loop, using it, then freeing it at the end of the while loop and took out the allocation in the list_add() function. This didn't work either />. How to stop the leakage.
I have changed my const global int NUMLABS to a non constant variable so that the user can decide how many labs to input. I adjusted the parameters of each function to add NUMLABS becuase the variable is no longer constant. But now main() returns 0 right after the user chooses how many stations to put in each lab. I am having difficulty understanding these dynamically allocated arrays.
This program uses dynamic arrays to store login information for four labs. Each of the four labs is referenced by the labs[] array which is indexed from 0-3. A pointer in the labs[] array then references a dynamic array that is of size for however many computers are in that lab.
Written by: Luca Del Signore Last modified on: October 3rd Known bugs: N/A *********************************************************************/ #include <iostream> #include <cstdlib> using namespace std;
I am struggling to finish up my game of War. There are a few problems I have ran in to. My shuffle function seems to work fine. I believe my problem lies within my game rules. When I run my code, the game usually plays all the way through but almost always ends in 'War'. I am struggling to get the game to restart after running once. I am not sure how to clear the list and start over.
Suppose I wished to initialize a dynamically allocated array of integers to zero. Would I do better to use calloc() or malloc + iterate over all entries setting each to zero? Which one is regarded as a better approach?
void readFile(struct course *d, char* filename){ FILE* fp; char buffer[100]; int i = 0, array_size = 100; struct course *temp;
[code]....
I will be using this to read data from a file. I start with an array of 100 structures being passed to the readfile function. Once it reads 100 lines (i == array_size), I want to double the array size until I have finished reading the file.
Two questions.
1)My initial thought was that I needed to keep track of the lines read with my variable, i. However, is there a better way?
2)My program is crashing right now at the call to double_array_size function. What is wrong with my code? Never dealt with dynamically allocated array of structures and functions.
I read online that I should change my code in the following manner.
I can paste the "error messages" if you like, but it is a page full of stuff I have never seen. glibc detected, Backtrace, Memory Map, and a bunch of numbers and hexadecimal stuff like addresses.
I'm trying to read in a file and store it in an array that is dynamically allocated of a struct (which I'm not sure how to do), then parse each line using strtok() from string.h. The idea is to separate the lines by date, subject, time, etc.
Since the array is a dynamically allocated of typdef struct, it's sorted by the date of each struct, with an intial size of 25. But whenever the array needs to be resized, it should be doubled.
this is my function for allocating memory in 2D array
Code:
#include <stdio.h> #include <stdlib.h> int allocate_array(int **array, int *row, int *column){ int i; }
[code]....
end of allocate_array function and this is my function for asking for the values to be stored in array
Code:
int input_array(int **array, int row, int column){ int i, j; //ask for the values to be stored in the 2D array for( i = 0; i < row; i++ ){ for( j = 0; j < column; j++ ){ }
[code]....
why I'm having error here in my input_array() function
Just trying to fill a dynamically allocated array with values then I want to print out the values using pointer method:
#include <iostream> using namespace std; long * extend_arr(long int arr[], long int length, long int val) { long * array2 = new long [length + 1]; for (int J = 0; J < length; ++J) array2[J] = arr[J];
[Code] ....
When this runs, I get an array with random numbers in it. For example, just trying to print the first value in *Block gives me random numbers each time. What is wrong with this as to why it is not holding the right values?
The extend_arr works perfectly fine, because when I try to access the values in the array using indexes (arr[0], arr[1], etc) it shows the right output, but using pointers does not. How can I make it work?
This a very simple program I created because I dont understand how do this. My goal is to be able to use the pointer *s5 throughout the program. For example I would to like to call other functions and pass that pointer through the function. I understand the dynamic allocation and pointers for the most part but Im confused here because the "new char[20]" variable will die after the function and I dont want it to.
#include <iostream> #include <cstdlib> #include <cstring> using namespace std; void testArray ( char *s5 ); int main ( int argc, char *argv[] )
In a program I'm working on now, i need a milti-dimensional array. To save space, I used dynamically allocated array by using pointers, something like this-
int *arr; arr=new int[col*row];
And now i need to pass this array in a function. What are the parameters in the function declaration statement and at the function call statement?
I'm trying to write a function that returns a pointer to a dynamically allocated array. Here's my code:
#include <iostream> using namespace std; void IndexArray(int, int); int main(){ int *arr, n;
[Code] ....
When I try running the program, I get the error
"Unable to start program 'D:C++FilesdynamicArraySolReleasedynamicArray.exe'. The system cannot find the file specified."
I'm honestly not sure if the issue is my program, or something with C++. At the moment, I cannot debug any of my programs or else I get the same exact error. I basically need to release everything without debugging it. I last used C++ about a year ago and I'm finally back in school, and so trying to get back into it. I use Microsoft Visual C++ 2010.
When declaring char array[10], memory is allocated for 10 1-bit memory locations. Is extra memory allocated for storing the address of array[0]? In expressions, is array equivalent to a pointer constant or is it an identifier for a memory cell containing the address of array[0]? In other words, is array a variable or an alias for &array[0]?
I have a structure, containing a pointer as a member. I dynamically create an array of that structure type, and then need to dynamically create an array for its pointer member.
#include <iostream> #include <string> using namespace std;
[Code]....
There is more of my program afterwards, but it shouldn't matter. The errors I am getting at compile time are that I cannot convert an int pointer to an int (line 29) and that test is not a member of CourseGrade (lines 44/45).
My thought is I might be using the * operator incorrectly. My code before hand in line 29 was
for (i = 0; i < numberStudents; i++) *studentPtr[i]->tests = new int[numberTests];
but the compiler suggested a '.' rather then the '->'
I first want to say that i am trying to solve my code without Pointers.
My goal is to.. 1. Construct an empty 2D array with a capacity of 25. (list[25][2];) 2. Empty(): test if the stack is empty 3. Push(): add a value to the stack in the (list[i][0] = value;) position and (list[i][1] = previous list[i][0] position) 4. Top(); read the value(list[i][0]) at the top(count) of the stack 5. Pop(); remove the value at the top of the stack (list[i]= 0;) 6. Display(); displays all the elements in the stack going from the top to bottom order. (shows array index, data value, and next array index)
I have hit a road block and don't know what to fix or where to go from here.
I have the following dynamically allocated 2D array:
Code:
int num_rows = 100; int num_cols = 3; double **myArray= (double**)malloc( sizeof(double *) * num_rows); for(i = 0; i < num_rows; i++) { myArray[i] = (double*)malloc( sizeof(double) * num_cols); }
After sorting the array based on the values in column 1,:
Code:
qsort(myArray, num_rows, sizeof(myArray[0]), comp_function); int comp_function(const void* a, const void* b) { double **p1 = (double**)a; double **p2 = (double**)b; double *arr1 = *p1; double *arr2 = *p2;
return arr1[0] - arr2[0]; }
I need to split the array into two halves so that I can pass each separately into another function that accepts a type double ** pointer. What is the most efficient way of splitting the array? Is it possible to keep the original double ** pointer for the first half of the array and then assign a new double ** pointer to the second half of the array?