void FreeParameterGroup (ParameterGroup *param_group_p)
{
	FreeCopiedString (param_group_p -> pg_name_s);

	if (param_group_p -> pg_key_s)
		{
			FreeCopiedString (param_group_p -> pg_key_s);
		}

	FreeLinkedList (param_group_p -> pg_child_groups_p);

	FreeLinkedList (param_group_p -> pg_params_p);

	FreeMemory (param_group_p);
}
Exemple #2
0
void FreeHashTable(HashTable table,
                   ValueFreeFnPtr value_free_function) {
  HWSize_t i;

  Verify333(table != NULL);  // be defensive

  // loop through and free the chains on each bucket
  for (i = 0; i < table->num_buckets; i++) {
    LinkedList  bl = table->buckets[i];
    HTKeyValue *nextKV;

    // pop elements off the the chain list, then free the list
    while (NumElementsInLinkedList(bl) > 0) {
      Verify333(PopLinkedList(bl, (LLPayload_t*)&nextKV));
      value_free_function(nextKV->value);
      free(nextKV);
    }
    // the chain list is empty, so we can pass in the
    // null free function to FreeLinkedList.
    FreeLinkedList(bl, LLNullFree);
  }

  // free the bucket array within the table record,
  // then free the table record itself.
  free(table->buckets);
  free(table);
}
Exemple #3
0
void FreeHashTable(HashTable table,
                   ValueFreeFnPtr value_free_function) {
  uint32_t i;

  // loop through and free the chains on each bucket
  for (i = 0; i < table->num_buckets; i++) {
    LinkedList  bl = table->buckets[i];
    HTKeyValue *nextKV;

    PopLinkedList(bl, (void **) &nextKV);
    // pop elements off the the chain list, then free the list
    while (NumElementsInLinkedList(bl) > 0) {
      value_free_function(nextKV->value);
      free(nextKV);
    }
    // the chain list is empty, so we can pass in the
    // null free function to FreeLinkedList.
    FreeLinkedList(bl, NullFree);
  }

  // free the bucket array within the table record,
  // then free the table record itself.
  free(table->buckets);
  free(table);
}
Exemple #4
0
Radar *InitializeRadar()
{
	Radar *radar_picture = NULL;
	radar_picture= (Radar *)malloc(sizeof(*radar_picture));

	LOG_INFO("InitializeRadar called");
	if (radar_picture == NULL)
	{
		LOG_ERROR("failed to allocate memory");
		return NULL; 
	}
	memset(radar_picture, '\0', sizeof(*radar_picture));

	radar_picture->foes = InitializeLinkedList();
	if (radar_picture->foes == NULL)
	{
		LOG_ERROR("failed to initialize foes list");
		free(radar_picture);
		return NULL;
	}

	radar_picture->friends = InitializeLinkedList();
	if (radar_picture->friends == NULL)
	{
		LOG_ERROR("failed to initialize friends list");
		FreeLinkedList(radar_picture->foes);
		free(radar_picture);
		return NULL; 
	}

	//When initializing the list, the threats foes are not updated. 
	radar_picture->is_friends_list_updated=FALSE;

	return radar_picture;
}
// our main function; here, we demonstrate how to use some
// of the linked list functions.
int main(int argc, char **argv) {
  ExamplePayloadPtr payload;
  LinkedListPtr list;
  LLIterPtr iter;
  int i;

  // allocate a list
  list = AllocateLinkedList();
  assert(list != NULL);

  // insert 100 elements
  for (i = 0; i < 100; i++) {
    payload = (ExamplePayloadPtr) malloc(sizeof(ExamplePayload));
    assert(payload != NULL);
    payload->num = i;
    assert(PushLinkedList(list, (void *) payload) == 1);

    // make sure our list total is correct
    assert(NumElementsInLinkedList(list) == i+1);
  }

  // sort the list in descending order
  SortLinkedList(list, 0, &ExamplePayloadComparator);

  // pop off the first element
  assert(PopLinkedList(list, (void **) &payload) == 1);
  assert(payload->num == 99);
  assert(NumElementsInLinkedList(list) == 99);
  free(payload);

  // slice off the last element
  assert(SliceLinkedList(list, (void **) &payload) == 1);
  assert(payload->num == 0);
  assert(NumElementsInLinkedList(list) == 98);
  free(payload);

  // make an iterator from the head
  iter = LLMakeIterator(list, 0);
  assert(iter != NULL);

  // peek at the current iterator payload
  LLIteratorGetPayload(iter, (void **) &payload);
  assert(payload->num == 98);

  // move the iterator, peek at next payload
  assert(LLIteratorNext(iter) == 1);
  LLIteratorGetPayload(iter, (void **) &payload);
  assert(payload->num == 97);

  // free the iterator
  LLIteratorFree(iter);

  // free the linked list
  FreeLinkedList(list, &ExamplePayloadFree);
  return 0;
}
// This prints the searchresult from list
static void printResult(DocTable table, LinkedList list) {
  LLIter it = LLMakeIterator(list, 0);
  SearchResultPtr searchResult;
  do {
    LLIteratorGetPayload(it, (LLPayload_t*)&searchResult);
    printf("  %s (%d)\n", DTLookupDocID(table, searchResult->docid),
     searchResult->rank);
  } while (LLIteratorNext(it));
  LLIteratorFree(it);
  FreeLinkedList(list, free);
}
Exemple #7
0
HashTable AllocateHashTable(uint32_t num_buckets) {
  HashTable ht;
  uint32_t  i;

  // defensive programming
  if (num_buckets == 0) {
    return NULL;
  }

  // allocate the hash table record
  ht = (HashTable) malloc(sizeof(HashTableRecord));
  if (ht == NULL) {
    return NULL;
  }

  //initialize synchronization
  sem_init(&ht->wrt, 0, 1);
  sem_init(&ht->mutex, 0, 1);
  ht->readcount = 0;

  // initialize the record
  ht->num_buckets = num_buckets;
  ht->num_elements = 0;
  ht->buckets =
    (LinkedList *) malloc(num_buckets * sizeof(LinkedList));
  if (ht->buckets == NULL) {
    // make sure we don't leak!
    free(ht);
    return NULL;
  }
  for (i = 0; i < num_buckets; i++) {
    ht->buckets[i] = AllocateLinkedList();
    if (ht->buckets[i] == NULL) {
      // allocating one of our bucket chain lists failed,
      // so we need to free everything we allocated so far
      // before returning NULL to indicate failure.  Since
      // we know the chains are empty, we'll pass in a
      // free function pointer that does nothing; it should
      // never be called.
      uint32_t j;
      for (j = 0; j < i; j++) {
        FreeLinkedList(ht->buckets[j], NullFree);
      }
      free(ht);
      return NULL;
    }
  }
  return (HashTable) ht;
}
Exemple #8
0
int main( void )
{
  FILE *FilePointer = OpenFile(FilePointer, 'w'); // Open file for writing
  Node* Head = malloc(sizeof(Node));

  BootStrapFile(FilePointer); // Create our base file
  fclose(FilePointer); // Close the file

  FilePointer = OpenFile(FilePointer, 'r'); // Reopen the file for reading
  ReadFile(FilePointer, Head); // Read file into linked lists
  PrintLinkedList( Head ); // Print the linked list
  fclose(FilePointer);
  FreeLinkedList(&Head);

  Head = (Node* )realloc(Head, sizeof(Node));
  FilePointer = OpenFile(FilePointer, 'r');
  ReadFile( FilePointer, Head );
  ManualEntry( Head );
  fclose(FilePointer);
  FilePointer = OpenFile(FilePointer, 'w'); // Reopen the file for reading

  WriteToFile( FilePointer, Head );
  fclose( FilePointer );
  FreeLinkedList( &Head );

  Head = (Node* )realloc(Head, sizeof(Node));
  FilePointer = OpenFile(FilePointer, 'r');
  ReadFile( FilePointer, Head );

  UpdateRecord( Head ); // Update record
  PrintLinkedList( Head );

  DeleteRecord( Head );
  PrintLinkedList( Head );

}
Exemple #9
0
BOOL FreeRadarList (LinkedList * list)
{
	RadarListNode *current_radar_object = NULL;
	if (list != NULL)
	{
		current_radar_object = (RadarListNode *)list->head;
		while (current_radar_object != NULL)
		{                 
			//free the memory malloc for the string holsing the name
			free (current_radar_object->entry->name);
			//free each radar object in the list
			free (current_radar_object->entry);
			current_radar_object=current_radar_object->next;
		}

		if (FreeLinkedList(list) == FALSE) //free the list itself
		{
			LOG_ERROR("Failed to fre the linked list");
			return FALSE;
		}
	}
	return TRUE;
}
void FreeDelaunayTriangulation(DelaunayTriangulation* dt)
{
  free(dt->m_AlphaSimplex);
  FreeStack(dt->m_RemovedSimplices, free);
  
  while(!IsEmpty(dt->m_RemovedVoronoiCells))
  {
    VoronoiCell* voronoiCell = (VoronoiCell*)Pop(dt->m_RemovedVoronoiCells);
    int i;
    for (i = 0;i < voronoiCell->m_NumPointsAlloc; i++)
      free(voronoiCell->m_Points[i]);
    free(voronoiCell->m_Points);
    FreeArrayList(voronoiCell->m_Vertices, nullptr);
    free(voronoiCell);
  }
  
  FreeStack(dt->m_RemovedVoronoiCells, nullptr);
  FreeLinkedList(dt->m_Simplices, free);
  FreeArrayList(dt->m_Conflicts, free);
  FreeArrayList(dt->m_Updates, nullptr);
  FreeNeighbourUpdates(dt->m_NeighbourUpdates);
  free(dt); 
}
LinkedList *GetMatchingFiles (const char * const pattern)
{
	LinkedList *list_p = AllocateLinkedList (FreeStringListNode);

	if (list_p)
		{
			WIN32_FIND_DATA file_data;
			char filename [MAX_PATH + 1];
			HANDLE handle;
			size_t len = strlen (pattern);

			if (len <= MAX_PATH)
				{
					strcpy (filename, pattern);

					if ((handle = FindFirstFile (filename, &file_data)) != INVALID_HANDLE_VALUE)
						{
							uint32 value = (file_data.dwFileAttributes) & FILE_ATTRIBUTE_DIRECTORY;

							if (value != FILE_ATTRIBUTE_DIRECTORY)
								{
									StringListNode *node_p = AllocateStringListNode (file_data.cFileName, MF_DEEP_COPY);
									if (node_p)
										{
											LinkedListAddTail (list_p, (ListNode *) node_p);
										}

									while (FindNextFile (handle, &file_data))
										{
											value = (file_data.dwFileAttributes) & FILE_ATTRIBUTE_DIRECTORY;
											if (value != FILE_ATTRIBUTE_DIRECTORY)
												{
													node_p = AllocateStringListNode (file_data.cFileName, MF_DEEP_COPY);
													if (node_p)
														{
															LinkedListAddTail (list_p, (ListNode *) node_p);
														}

												}
										}
								}

							if (! (FindClose (handle)))
								{
									// couldn't close search handle
								}
						}
				}

			if (list_p -> ll_size > 0)
				{
					return list_p;
				}
			else
				{
					FreeLinkedList (list_p);
				}
		}

	return NULL;
}
Exemple #12
0
json_t *AddExternalServerOperationsToJSON (ServersManager *manager_p, LinkedList *internal_services_p, Operation op)
{
	/* build the request that we will send to each external server */
	json_error_t error;
	json_t *op_p = json_pack ("{s:{s:i}}", SERVER_OPERATIONS_S, OPERATION_ID_S, op);
	json_t *ops_array_p = NULL;

	if (op_p)
		{
			LinkedList *servers_p = GetAllExternalServersFromServersManager (manager_p, DeserialiseExternalServerFromJSON);

			if (servers_p && (servers_p -> ll_size > 0))
				{
					ExternalServerNode *node_p = (ExternalServerNode *) servers_p -> ll_head_p;

					while (node_p)
						{
							ExternalServer *external_server_p = node_p -> esn_server_p;
							const char *response_s = MakeRemoteJsonCallViaConnection (external_server_p -> es_connection_p, op_p);

							if (response_s)
								{
									json_t *server_response_p = json_loads (response_s, 0, &error);

									/*
									 * If the external server has paired services, try and pair them
									 */

									if (server_response_p)
										{
											json_t *default_external_provider_p = json_object_get (server_response_p, SERVER_PROVIDER_S);

											#if SERVERS_POOL_DEBUG >= STM_LEVEL_FINE
											PrintJSONToLog (ops_array_p, "local server json:\n", STM_LEVEL_FINE, __FILE__, __LINE__);
											PrintJSONToLog (default_external_provider_p, "default_external_provider_p:\n", STM_LEVEL_FINE, __FILE__, __LINE__);
											#endif



											/*
											 * The elements to get are dependent on the api call
											 */
											switch (op)
												{
													case OP_LIST_ALL_SERVICES:
													case OP_LIST_INTERESTED_SERVICES:
													case OP_GET_NAMED_SERVICES:
														{
															json_t *src_services_p = json_object_get (server_response_p, SERVICES_NAME_S);

															if (src_services_p)
																{
																	json_t *src_ops_p = json_object_get (src_services_p, SERVER_OPERATIONS_S);

																	if (src_ops_p)
																		{
																			#if SERVERS_POOL_DEBUG >= STM_LEVEL_FINE
																			PrintJSONToLog (src_ops_p, "src_ops:\n", STM_LEVEL_FINE, __FILE__, __LINE__);
																			#endif

																			if (json_is_array (src_ops_p))
																				{
																					json_t *dest_p = json_object ();

																					if (dest_p)
																						{
																							/*
																							 * If the op doesn't have an explicit provider, add
																							 * the default one
																							 */
																							bool success_flag = true;
																							json_t *provider_p = json_object_get (server_response_p, SERVER_PROVIDER_S);

																							if (!provider_p)
																								{
																									provider_p = default_external_provider_p;
																								}

																							if (provider_p)
																								{
																									if (json_object_set (dest_p, SERVER_PROVIDER_S, provider_p) != 0)
																										{
																											success_flag = false;
																										}
																								}

																							if (success_flag)
																								{
																									success_flag = false;

																									if (json_object_set (dest_p, SERVER_OPERATIONS_S, src_ops_p) == 0)
																										{
																											if (json_array_append_new (ops_array_p, dest_p) == 0)
																												{
																													success_flag = true;
																												}
																										}
																								}		/* if (success_flag) */

																							if (!success_flag)
																								{
																									WipeJSON (dest_p);
																								}


																						}		/* if (dest_p) */

																				}		/* if (json_is_array (src_ops_p)) */

																		}		/* if (src_ops_p) */

																}		/* if (src_services_p) */
														}

														break;

													case OP_RUN_KEYWORD_SERVICES:
													case OP_GET_SERVICE_RESULTS:
													//	element_name_s = SERVICE_RESULTS_S;
														break;

													case OP_IRODS_MODIFIED_DATA:
														break;

													case OP_CHECK_SERVICE_STATUS:
														break;

													case OP_CLEAN_UP_JOBS:
														break;

													default:
														break;
												}

											WipeJSON (server_response_p);

										}		/* if (server_response_p) */
									else
										{

										}

								}		/* if (response_s) */
							else
								{

								}

							node_p = (ExternalServerNode *) node_p -> esn_node.ln_next_p;
						}		/* while (node_p) */

					FreeLinkedList (servers_p);
				}		/* if (servers_p) */

			WipeJSON (op_p);
		}		/* if (op_p) */
	else
		{

		}


	#if SERVERS_POOL_DEBUG >= STM_LEVEL_FINE
	PrintJSONToLog (ops_array_p, "final ops p:\n", STM_LEVEL_FINE, __FILE__, __LINE__);
	#endif

	return ops_array_p;
}
Exemple #13
0
LinkedList *GetMatchingFiles (const char * const pattern, const bool full_path_flag)
{
	LinkedList *list_p = AllocateLinkedList (FreeStringListNode);

	if (list_p)
		{
			char *filename_p = GetFilenameOnly (pattern);

			if (filename_p)
				{
					char *path_p = GetPathOnly (pattern);

					if (path_p)
						{
							DIR *dir_p = opendir (path_p);

							if (dir_p)
								{
									struct dirent entry;
									struct dirent *entry_p = &entry;

									while ((entry_p = readdir (dir_p)) != NULL)
										{
											if ((fnmatch (filename_p, entry_p -> d_name, 0)) == 0)
												{
													StringListNode *node_p = NULL;

													if (full_path_flag)
														{
															char *full_filename_s = MakeFilename (path_p, entry_p -> d_name);

															if (full_filename_s)
																{
																	node_p = AllocateStringListNode (full_filename_s, MF_SHALLOW_COPY);
																}
														}
													else
														{
															node_p = AllocateStringListNode (entry_p -> d_name, MF_DEEP_COPY);
														}

													if (node_p)
														{
															LinkedListAddTail (list_p, (ListItem *) node_p);
														}
												}
										}

									closedir (dir_p);
								}

							FreeMemory (path_p);
						}

					FreeMemory (filename_p);
				}


			if (list_p -> ll_size > 0)
				{
					return list_p;
				}
			else
				{
					FreeLinkedList (list_p);
				}
		}

	return NULL;
}
Exemple #14
0
ParameterGroup *AllocateParameterGroup (const char *name_s, const char *key_s, ServiceData *service_data_p)
{
	char *copied_name_s = CopyToNewString (name_s, 0, false);

	if (copied_name_s)
		{
			LinkedList *children_p = NULL;
			char *copied_key_s = NULL;

			if (key_s)
				{
					copied_key_s = CopyToNewString (key_s, 0, false);

					if (!copied_key_s)
						{
							PrintErrors (STM_LEVEL_SEVERE, __FILE__, __LINE__, "Failed to copy key \"%s\"", key_s);
							FreeCopiedString (copied_name_s);
							return NULL;
						}
				}

			children_p = AllocateLinkedList (FreeParameterGroupNode);

			if (children_p)
				{
					/*
					 * The Parameters stored on this List are also known
					 * to the ParameterSet which is where they will get
					 * freed. So all we need to do on this LinkedList
					 * is free the memory allocated for the nodes.
					 */
					LinkedList *params_p = AllocateLinkedList (NULL);

					if (params_p)
						{
							ParameterGroup *param_group_p = (ParameterGroup *) AllocMemory (sizeof (ParameterGroup));

							if (param_group_p)
								{
									param_group_p -> pg_name_s = copied_name_s;
									param_group_p -> pg_key_s = copied_key_s;
									param_group_p -> pg_params_p = params_p;
									param_group_p -> pg_visible_flag = true;

									param_group_p -> pg_full_display_flag = true;
									param_group_p -> pg_vertical_layout_flag = true;
									param_group_p -> pg_child_groups_p = children_p;

									if (service_data_p)
										{
											GetParameterGroupVisibility (service_data_p, name_s, & (param_group_p -> pg_visible_flag));
										}

									return param_group_p;
								}

							FreeLinkedList (params_p);
						}		/* if (params_p) */

					FreeLinkedList (children_p);
				}


			FreeCopiedString (copied_name_s);
		}		/* if (copied_name_s) */

	return NULL;
}
// A private function for freeing a WordHT.
static void WordHTFree(HTValue_t payload) {
  WordPositions *pos = (WordPositions *) payload;
  FreeLinkedList(pos->positions, &NullWPListFree);
  free(pos->word);
  free(pos);
}
int main(int argc, char **argv) {
  if (argc != 2)
    Usage();

// Implement searchshell!  We're giving you very few hints
// on how to do it, so you'll need to figure out an appropriate
// decomposition into functions as well as implementing the
// functions.  There are several major tasks you need to build:
//
//  - crawl from a directory provided by argv[1] to produce and index
//  - prompt the user for a query and read the query from stdin, in a loop
//  - split a query into words (check out strtok_r)
//  - process a query against the index and print out the results
//
// When searchshell detects end-of-file on stdin (cntrl-D from the
// keyboard), searchshell should free all dynamically allocated
// memory and any other allocated resources and then exit.

  DocTable doctable;
  MemIndex index;
  int qlen, res;
  char *query[128];
  char *input = (char*) malloc(128);
  char *token;
  char *check;
  char *saveptr;
  LinkedList retlist;
  LLIter llit;
  SearchResult *sres;
  char *name;


  // crawls the directory
  printf("Indexing '%s'\n", argv[1]);
  // gets the doctable and inverted index table
  res = CrawlFileTree(argv[1], &doctable, &index);
  if (res == 0) {  // encounters error
    Usage();
  }

  while (1) {
    printf("enter query:\n");
    // when the user types control-D
    if (fgets(input, 128, stdin) == NULL) {
      printf("shutting down...\n");
      break;
    }
    qlen = 0;

    // gets the first token
    token = strtok_r(input, " ", &saveptr);
    // stores the token in the array
    while (token != NULL) {
      query[qlen] = token;
      qlen++;
      token = strtok_r(NULL, " ", &saveptr);
    }
    // changes \n to \0
    check = strchr(query[qlen - 1], '\n');
    if (check != NULL) {
      *check = '\0';
    }

    // gets the result linkedlist
    retlist = MIProcessQuery(index, query, qlen);
    if (retlist != NULL && NumElementsInLinkedList(retlist) != 0) {
      // iterates through the list and print
      llit = LLMakeIterator(retlist, 0);
      Verify333(llit != NULL);
      do {
        // prints the result from the iterator
        LLIteratorGetPayload(llit, (void **)&sres);
        name = DTLookupDocID(doctable, sres->docid);
        printf("  %s  (%d)\n", name, sres->rank);
      } while (LLIteratorNext(llit));

      LLIteratorFree(llit);  // free the iterator
      FreeLinkedList(retlist, free);  // free the linked list
    }
  }

  free(input);
  FreeDocTable(doctable);
  FreeMemIndex(index);
  return EXIT_SUCCESS;
}
Exemple #17
0
/**
 * Parse the format string and sort out into a linked
 * list of items.
 *
 * @param format_p The format string to use.
 * @param allocate_list_fn The function used to create the LinkedList.

 * @return A pointer to a LinkedList where each node
 * refers to a token or NULL upon error.
 */
static LinkedList *ParseStringToLinkedList (const char * const format_p, const char * const delimiters_p, LinkedList *(*allocate_list_fn) (void), ListItem *(*allocate_node_fn) (const char *value_s), const bool treat_whitespace_as_delimiter_flag)
{
	LinkedList *tokens_list_p = NULL;
	const char *index_p = format_p;

	if (index_p)
		{
			tokens_list_p = allocate_list_fn ();

			if (tokens_list_p)
				{
					const char *ptr = format_p;
					bool loop_flag = true;
					bool error_flag = false;
					char *copy_p = NULL;

					while (loop_flag)
						{
							/* scroll past any delimiters */
							char *value_s = GetNextToken (&ptr, delimiters_p, treat_whitespace_as_delimiter_flag, true);

							if (value_s)
								{
									ListItem *node_p = allocate_node_fn (value_s);

									if (node_p)
										{
											LinkedListAddTail (tokens_list_p, node_p);

											/*
											ptr = strtok (NULL, delimiters_p);
											loop_flag = (ptr != NULL);
											*/
										}
									else
										{
											loop_flag = false;
											error_flag = true;
										}

									FreeCopiedString (value_s);
								}		/* if (value_s) */
							else
								{
									loop_flag = false;
								}

						}		/* while (loop_flag) */

					if (error_flag)
						{
							FreeLinkedList (tokens_list_p);
							tokens_list_p = NULL;
						}

					FreeMemory (copy_p);


					/* If the list is empty, don't return it */
					if (tokens_list_p && (tokens_list_p-> ll_size == 0))
						{
							FreeLinkedList (tokens_list_p);
							tokens_list_p = NULL;
						}

				}		/* if (tokens_list_p) */

		}		/* if (index_p) */

	return tokens_list_p;
}