I am fairly new to C and have been having a lot of difficulty trying to copy the values of an array of pointers to strings. I have created a struct that contains such a pointer array (part of an implementation of a doubly linked list)
typedef struct Node
{
int value;
char *args[41];
....
} Node;
When I want to add a node, I have been using the following method
void addNew(char *args[], Node *current)
{
// first node is passed in, so loop until end of list is reached
while ((*current).next != NULL
current = (*current).next;
// create new node that is linked with the last node
(*current).next = (Node *)malloc(sizeof(Node));
((*current).next)).prev = current;
current = (*current).next;
// assign value to new node
(*current).value = some-new-value;
// allocate space for new argument array
(*current).args[41] = (char*)malloc(41 * sizeof(char*));
int i=0;
// loop through the arg array and copy each of the passed-in args into the node
for (i=0; i<41; i++)
strcpy((*current).args[i], args[i]);
(*current).next = NULL;
}
I think the root of my problem is in how I am allocating space for the pointers in the new node, but I haven't been able to figure out what I was doing wrong. As it stands, I get a Segmentation Fault (core dumped) as soon as the strcpy line is reached.
Any idea what Im doing wrong?
The line
(*current).args[41] = (char*)malloc(41 * sizeof(char*));
does not make sense at all. I am not sure what you were trying to accomplish there. Remove that line.
In order to be able to use:
for (i=0; i<41; i++)
strcpy((*current).args[i], args[i]);
you need to allocate memory for each element of (*current).args. Here's one way:
for (i=0; i<41; i++)
{
int len = strlen(args[i]);
(*current).args[i] = malloc(len+1);
strcpy((*current).args[i], args[i]);
}
Related
I have a block of pointers to some structs which I want to handle (i.e. free) separately. As an example below there is an integer double-pointer which should keep other pointers to integer. I then would like to free the second of those integer pointers (in my program based on some filterings and calculations). If I do so however, I should keep track of int-pointers already set free so that when I iterate over the pointers in the double-pointer I do not take the risk of working with them further. Is there a better approach for solving this problem (in ANSI-C) without using other libs (e.g. glib or alike)?
Here is a small simulation of the problem:
#include <stdio.h>
#include <stdlib.h>
int main() {
int **ipp=NULL;
for (int i = 0; i < 3; i++) {
int *ip = malloc(sizeof (int));
printf("%p -> ip %d\n", ip, i);
*ip = i * 10;
if ((ipp = realloc(ipp, sizeof (int *) * (i + 1)))) {
ipp[i] = ip;
}
}
printf("%p -> ipp\n", ipp);
for (int i = 0; i < 3; i++) {
printf("%d. %p %p %d\n", i, ipp + i, *(ipp+i), **(ipp + i));
}
// free the middle integer pointer
free(*(ipp+1));
printf("====\n");
for (int i = 0; i < 3; i++) {
printf("%d. %p %p %d\n", i, ipp + i, *(ipp+i), **(ipp + i));
}
return 0;
}
which prints something like
0x555bcc07f2a0 -> ip 0
0x555bcc07f6f0 -> ip 1
0x555bcc07f710 -> ip 2
0x555bcc07f6d0 -> ipp
0. 0x555bcc07f6d0 0x555bcc07f2a0 0
1. 0x555bcc07f6d8 0x555bcc07f6f0 10
2. 0x555bcc07f6e0 0x555bcc07f710 20
====
0. 0x555bcc07f6d0 0x555bcc07f2a0 0
1. 0x555bcc07f6d8 0x555bcc07f6f0 0
2. 0x555bcc07f6e0 0x555bcc07f710 20
Here I have freed the middle int-pointer. In my actual program I create a new block for an integer double-pointer, iterate over the current one, create new integer pointers and copy the old values into it, realloc the double-pointer block and append the new pointer to it, and at the end free the old block and all it's containing pointers. This is a bit ugly, and resource-consuming if there is a huge amount of data, since I have to iterate over and create and copy all the data twice. Any help is appreciated.
Re:
"This is a bit ugly, and resource-consuming if there is a huge amount of data, since I have to iterate over and create and copy all the data
twice. Any help is appreciated."
First observation: It is not necessary to use realloc() when allocating new memory on a pointer that has already been freed. realloc() is useful when needing to preserve the contents in a particular area of memory, while expanding its size. If that is not a need (which is not in this case) malloc() or calloc() are sufficient. #Marco's suggestion is correct.
Second observation: the following code snippet:
if ((ipp = realloc(ipp, sizeof (int *) * (i + 1)))) {
ipp[i] = ip;
}
is a potential memory leak. If the call to realloc()_ fails, the pointer ipp will be set to null, making the memory location that was previously allocated becomes orphaned, with no way to free it.
Third observation: Your approach is described as needing:
Array of struct
dynamic memory allocation of a 2D array
need to delete elements of 2D array, and ensure they are not referenced once deleted
need to repurpose deleted elements of 2D array
Your initial reaction in comments to considering using an alternative approach notwithstanding, Linked lists are a perfect fit to address the needs stated in your post.
The fundamental element of a Linked List uses a struct
Nodes (elements) of a List are dynamically allocated when created.
Nodes of a List are not accessible to be used once deleted. (No need to track)
Once the need exists, a new node is easily created.
Example struct follows. I like to use a data struct to contain the payload, then use an additional struct as the conveyance, to carry the data when building a Linked List:
typedef struct {//to simulate your struct
int dNum;
char unique_name[30];
double fNum;
} data_s;
typedef struct Node {//conveyance of payload, forward and backward searchable
data_s data;
struct Node *next; // Pointer to next node in DLL
struct Node *prev; // Pointer to previous node in DLL
} list_t;
Creating a list is done by creating a series of nodes as needed during run-time. Typically as records of a database, or lines of a file are read, and the elements of the table record (of element of the line in a file) are read into and instance of the data part of the list_s struct. A function is typically defined to do this, for example
void insert_node(list_s **head, data_s *new)
{
list_s *temp = malloc(sizeof(*temp));
//insert lines to populate
temp.data.dNum = new.dNum;
strcpy(temp.data.unique_name, new.unique_name);
temp.fNum = new.fNum
//arrange list to accomdate new node in new list
temp->next = temp->prev = NULL;
if (!(*head))
(*head) = temp;
else//...or existing list
{
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
Deleting a node can be done in multiple ways. It the following example method a unique value of a node member is used, in this case unique_name
void delete_node_by_name(list_s** head_ref, const char *name)
{
BOOL not_found = TRUE;
// if list is empty
if ((*head_ref) == NULL)
return;
list_s *current = *head_ref;
list_s *next = NULL;
// traverse the list up to the end
while (current != NULL && not_found)
{
// if 'name' in node...
if (strcmp(current->data.unique_name, name) == 0)
{
//set loop to exit
not_found = FALSE;
//save current's next node in the pointer 'next' /
next = current->next;
// delete the node pointed to by 'current'
delete_node(head_ref, current);
// reset the pointers
current = next;
}
// increment to next node
else
{
current = current->next;
}
}
}
Where delete_node() is defined as:
void delete_node(list_t **head_ref, list_t *del)
{
// base case
if (*head_ref == NULL || del == NULL)
return;
// If node to be deleted is head node
if (*head_ref == del)
*head_ref = del->next;
// Change next only if node to be deleted is NOT the last node
if (del->next != NULL)
del->next->prev = del->prev;
// Change prev only if node to be deleted is NOT the first node
if (del->prev != NULL)
del->prev->next = del->next;
// Finally, free the memory occupied by del
free(del);
}
This link is an introduction to Linked Lists, and has additional links to other related topic to expand the types of lists that are available.
You could use standard function memmove and then call realloc. For example
Let's assume that currently there are n pointers. Then you can write
free( *(ipp + i ) );
memmove( ipp + i, ipp + i + 1, ( n - i - 1 ) * sizeof( *pp ) );
*( ipp + n - 1 ) = NULL; // if the call of realloc will not be successfull
// then the pointer will be equal to NULL
int **tmp = realloc( ipp, ( n - 1 ) * sizeof( *tmp ) );
if ( tmp != NULL )
{
ipp = tmp;
--n;
}
else
{
// some other actions
}
I'm still learning how to program in C and I've stumbled across a problem.
Using a char array, I need to create a linked list, but I don't know how to do it. I've searched online, but it seems very confusing. The char array is something like this char arr[3][2]={"1A","2B","3C"};
Have a look at this code below. It uses a Node struct and you can see how we iterate through the list, creating nodes, allocating memory, and adding them to the linked list. It is based of this GeeksForGeeks article, with a few modifications. I reccommend you compare the two to help understand what is going on.
#include <stdio.h>
#include <stdlib.h>
struct Node {
char value[2];
struct Node * next;
};
int main() {
char arr[3][2] = {"1A","2B","3C"};
struct Node * linked_list = NULL;
// Iterate over array
// We calculate the size of the array by using sizeof the whole array and dividing it by the sizeof the first element of the array
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
// We create a new node
struct Node * new_node = (struct Node *)malloc(sizeof(struct Node));
// Assign the value, you can't assign arrays so we do each char individually or use strcpy
new_node->value[0] = arr[i][0];
new_node->value[1] = arr[i][1];
// Set next node to NULL
new_node->next = NULL;
if (linked_list == NULL) {
// If the linked_list is empty, this is the first node, add it to the front
linked_list = new_node;
continue;
}
// Find the last node (where next is NULL) and set the next value to the newly created node
struct Node * last = linked_list;
while (last->next != NULL) {
last = last->next;
}
last->next = new_node;
}
// Iterate through our linked list printing each value
struct Node * pointer = linked_list;
while (pointer != NULL) {
printf("%s\n", pointer->value);
pointer = pointer->next;
}
return 0;
}
There are a few things the above code is missing, like checking if each malloc is successful, and freeing the allocated memory afterwards. This is only meant to give you something to build off of!
I have a function that takes an array of strings. It separates all those strings by the presence of a particular character, in this case '|'. See my previous question for a better idea Split an array of strings based on character
So, I have an array of strings that looks like this:
char ** args = {"ls", "-l", "|", "cd", "."}
My parseCmnds function is supposed to go through each string in the array and create a new array of strings with all the strings before the '|' character. Then it creates a linked list where each node points to each of the array of strings I created, essentially separating the original array of strings into separate arrays of strings linked to each other.
So, my parse loop should create something like this for example:
On the first iteration:
char ** command = {"ls", "-l", NULL}
On the second iteration
char ** command = {"cd", ".", NULL}
After each iteration my function creates a new linked list node and populates it. I built code based on some of the answers I got on my previous question (thanks a million). But for some reason I'm getting a segmentation fault that I can't figure out. Can someone check out my code and let me know what I'm doing wrong?
typedef struct node {
char ** cmnd;
struct node * next;
} node_cmnds;
node_cmnds * parseCmnds(char **args) {
int i;
int j=0;
int numArgs = 0;
node_cmnds * head = NULL; //head of the linked list
head = malloc(sizeof(node_cmnds));
if (head == NULL) { //allocation failed
return NULL;
}
else {
head->next = NULL;
}
node_cmnds * currNode = head; //point current node to head
for(i = 0; args[i] != NULL; i++) { //loop that traverses through arguments
char ** command = (char**)malloc(maxArgs * sizeof(char*)); //allocate an array of strings for the command
if(command == NULL) { //allocation failed
return NULL;
}
while(strcmp(args[i],"|") != 0) { //loop through arguments until a | is found
command[i] = (char*)malloc(sizeof(args[i])); //allocate a string to copy argument
if(command[i] == NULL) { //allocation failed
return NULL;
}
else {
strcpy(command[i],args[i]); //add argument to our array of strings
i++;
numArgs++;
}
}
command[i] = NULL; //once we find | we set the array element to NULL to specify the end
while(command[j] != NULL) {
strcpy(currNode->cmnd[j], command[j]);
j++;
}
currNode->next = malloc(sizeof(node_cmnds));
if(currNode->next == NULL) {
return NULL;
}
currNode = currNode->next; //
numArgs = 0;
}
return head;
}
You're never allocating any memory for the cmnd member of node_cmds. So the line strcpy(currNode->cmnd[j], command[j]); is writing to...somewhere. Likely to memory you don't own. And when you do add those mallocs, your indexing (using j) is going to be very incorrect on the second pass through the outside for loop.
Also, you're leaking memory like a sieve. Try throwing some frees in there.
while(command[j] != NULL) {
strcpy(currNode->cmnd[j], command[j]);
j++;
}
At this statement you haven't allocated memory for the cmnd pointer(string). I believe this may be causing part of your problem. You have allocated memory for the struct, but you need to allocate memory for each pointer in the struct as well.
I have the following structure:
typedef struct TRIE_NODE
{
char* word;
struct TRIE_NODE* node[26];
}TRIE_NODE;
I create a node called head, TRIE_NODE *head = NULL;, and then i try to initialize this node using the following function:
void initialize_node(TRIE_NODE *current_node)
{
int MAX = 25;
current_node = malloc(sizeof(TRIE_NODE));
for(int i = 0; i < MAX; i++)
{
current_node->node[i] = NULL;
if(current_node->node[i] == NULL)
printf("\n -- \n");
}
}
However, i get a segmentation fault whenever i try to even read current_node->node[i]. Does anyone have any idea of what's going on? Considering current_node->node is a pointer, that points to another pointer of type TRIE_NODE, shouldn't i be able to access it's values through bracket notation? (I've tried dereferencing it too, it doesn't compile)
You do everything correctly, except this line
current_node = malloc(sizeof(TRIE_NODE));
which modifies the local copy of current_node. The pointer in the caller remains unchanged.
To fix this problem, pass a pointer to pointer, and assign with an indirection operator:
void initialize_node(TRIE_NODE **current_node_ptr) {
...
*current_node_ptr = malloc(sizeof(TRIE_NODE));
...
}
I am trying to insert an integer into a hash table. To do this, I'm creating an array of node*'s and I'm trying to make assignments like listarray[i]->data=5 possible. However, I'm still very confused with pointers and I'm crashing at the line with the comment '//crashes here' and I don't understand why. Was my initialization in main() invalid?
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node * next;
} node;
//------------------------------------------------------------------------------
void insert (node **listarray, int size)
{
node *temp;
int value = 11; //just some random value for now, eventually will be scanned in
int index = value % size; // 11 modulo 8 yields 3
printf ("index is %d\n", index); //prints 3 fine
if (listarray[index] == NULL)
{
printf("listarray[%d] is NULL",index); //prints because of loop in main
listarray[index]->data = value; //crashes here
printf("listarray[%d] is now %d",index,listarray[index]->data); //never prints
listarray[index]->next = NULL;
}
else
{
temp->next = listarray[index];
listarray[index] = temp;
listarray[index]->data = value;
}
}//end insert()
//------------------------------------------------------------------------------
int main()
{
int size = 8,i; //set default to 8
node * head=NULL; //head of the list
node **listarray = malloc (sizeof (node*) * size); //declare an array of Node *
//do i need double pointers here?
for (i = 0; i < size; i++) //malloc each array position
{
listarray[i] = malloc (sizeof (node) * size);
listarray[i] = NULL; //satisfies the first condition in insert();
}
insert(*&listarray,size);
}
output:
index is 3
listarray[3] is NULL
(crash)
desired output:
index is 3
listarray[3] is NULL
listarray[3] is now 11
There are various issues here:
If you have a hash table of a certain size, then the hash code must map to a value between 0 and size - 1. Your default size is 8, but your hash code is x % 13, which means that your index might be out of bounds.
Your insert function should also pass the item to insert (unless that's the parameter called size, in which case it is severely misnamed).
if (listarray[index] == NULL) {
listarray[index]->data = value; //crashes here
listarray[index]->next = NULL;
}
It's no wonder that it crashes: When the node is NULL, you cannot dereference it with either * or ->. You should allocate new memory here.
And you shouldn't allocate memory here:
for (i = 0; i < size; i++) //malloc each array position
{
listarray[i] = malloc (sizeof (node) * size);
listarray[i] = NULL; //satisfies the first condition in insert();
}
Allocating memory and then resetting it to NULL is nonsense. NULL is a special value that means that no memory is at the pointed-to location. Just set all nodes to NULL, which means that the hash table starts out without any nodes. Allocate when you need a node at a certain position.
In the else clause, you write:
else
{
temp->next = listarray[index];
listarray[index] = temp;
listarray[index]->data = value;
}
but temp hasn't been allocated, but you dereference it. That's just as bad as dereferencing ´NULL`.
Your hash table also needs a means to handle collisions. It looks as if at every index in the hash table, there is a linked list. That's a good way to deal with it, but you haven't implemented it properly.
You seem to have problems to understand pointers. Perhaps you should start with a simpler data structure like a linked list, just to practice? When you have gotten a firm grasp of that, you can use what you've learned to implement your hash table.