I'm trying to run a function that deletes the nth element of the linked list (using zero-based indexing). Even though I don't have to necessarily malloc anything, I'm getting this error: "ev(10676,0x7fff73f9d300) malloc: * error for object 0x7fddc2404c10: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug"
Here is the code:
typedef struct intlist intlist;
struct intlist {
int val;
intlist* next;
intlist* intlist_remove_nth(intlist *xs, unsigned int n)
{
int i = 0;
if (n == 1)
{
intlist *tempremovefirst = xs->next;
free(xs);
return tempremovefirst;
}
intlist *temp = xs;
for (temp = xs; i != n - 1; i++)
{
temp = temp->next;
}
intlist *temp2 = temp->next;
temp->next = temp->next->next;
free(temp2);
return xs;
}
void evidence_intlist_remove_nth()
{
intlist *il1 = intlist_cons(1, NULL);
intlist *il2 = intlist_cons(4, il1);
intlist *il3 = intlist_cons(6, il2);
intlist *il4 = intlist_cons(8, il3);
intlist *il5 = intlist_cons(19, il4);
intlist *il6 = intlist_cons(24, il5);
intlist *il7 = intlist_cons(101, il6);
printf("expecting 101 24 19 6 4 1: ");
intlist_print(intlist_remove_nth(il7, 4));
printf("\n");
free(il1);
free(il2);
free(il3);
free(il4);
free(il5);
free(il6);
free(il7);
}
int main(int argc, char *argv[])
{
evidence_intlist_remove_nth();
return 0;
}
If you're not mallocing the items on the list, you shouldn't be freeing them. free() is only used to free memory that has been returned by malloc() or one of its relatives.
Related
I'm trying to copy a list into another list with memcpy, but I'm getting a segmentation fault everytime I try to access the value I copied.
I've already tried moving pointers around, but the problem still occurs.
create_list creates a new head node for the list and returns it. Here is some of the code:
/* The n variable shows the number of elements in the list for the head */
struct list {
union{
void *data;
struct {
unsigned num;
List *end;
};
};
List *node;
};
List *
create_list()
{
List *head;
head = malloc(sizeof(List));
if (head == NULL)
return NULL;
head->num = 0;
head->end = NULL;
head->node = NULL;
return head;
}
int
cpy_list(List *l1, List **l2)
{
List *iter;
void *data_aux;
*l2 = create_list();
iter = l1->node;
while (iter != l1->end) {
memcpy(&data_aux, iter->data, sizeof(iter->data));
//printf("data_aux: %s\n", data_aux);
insert_list(*l2, data_aux, NULL);
//printf("iter->data: %s\n", iter->data);
iter = iter->node;
}
return 1;
}
void
print_list(List *head)
{
List *iter;
iter = head->node;
printf("[");
while (iter != head->end) {
printf("\"%s\",", iter->data);
iter = iter->node;
}
printf("\"%s\"", iter->data);
printf("]");
printf("\n");
}
int
main(int argc, char *argv[])
{
List *l1, *l2;
char *str[] = {"Test0", "Test1", "Test2", "Test3", "Test4"};
void *data_aux;
l1 = create_list();
for (int k = 0; k < 5; k++) {
insert_list(l1 ,str[k], NULL);
}
printf("l1: ");
print_list(l1);
cpy_list(l1, &l2);
print_list(l2);
return 0;
}
memcpy(&data_aux, iter->data, sizeof(iter->data));
I'll assume this is a typo problem (let me know if it is not and you intended to use it like that). &data_aux will return the address of variable data_aux, not the address pointed by data_aux. This code is likely causing a stack overflow as you are probably
writing data beyond the boundaries of the local variable data_aux (which have the size of a pointer - 4 bytes on x86 or 8 bytes on x64). If iter->data have a significant size you will corrupt the stack and have undefined behavior.
What you probably want is to allocate a buffer to be pointed by data_aux. Something like:
data_aux = malloc(sizeof(iter->data));
And then pass data_aux instead of &data_aux in your call to memcpy.
I have written the following code:
typedef struct List {
struct List* next;
void *value;
} List;
void freeList(List* list, void destroyElement(void*)) {
while(list != NULL) {
destroyElement(list->value);
struct List* n = list;
list = list->next;
free(n);
}
}
struct List* arr2list(void** array, int length, void* cpyElement(void*), void (*destroyElement)(void*)) {
struct List* head = NULL;
struct List** tail = &head;
for(int i = 0; i < length; i++) {
*tail = calloc(1, sizeof(struct List));
printf("array[%d] = %d\n",i,*(((int*)array)+i));
if (*tail == NULL) {
freeList(head, destroyElement);
return NULL;
}
tail[0]->value = cpyElement(array[i]);
tail = &(tail[0]->next);
}
*tail = NULL;
return head;
}
void printList(List* list, void echoElement(void*)) {
while (list != NULL) {
echoElement(list->value);
list = list->next;
}
}
void destroyElement(void* el) {
if (el != NULL) {
struct List* node = el;
node->next = NULL;
free(node);
}
}
void* cpyElement(void* el) {
int *p = malloc(sizeof(*p));
*p = *(int *) el;
return p;
}
void echoElement(void* el) {
if (el != NULL) {
printf("%d ", *(int *) el);
}
}
int main(int argc, char** argv) {
int array_length = argc - 1;
int* array = (int*) malloc(sizeof(*array) * array_length);
for (int i = 0; i < array_length; i++){
*(array + i) = atoi(argv[i + 1]);
}
struct List* root = arr2list((void*) array,array_length,cpyElement, destroyElement);
printList(root,echoElement);
freeList(root,destroyElement);
free(array);
return 0;
}
The problem is with tail[0]->value = cpyElement(array[i]);. I get a segmentation fault error for this part. If I write it cpyElement(((int*)array)+i); it works but I want the function arr2list to be generic and not to mention int. How can I solve it? I think that I understand it's impossible to convert void* to int* because it does not know which size to use so is it possible to hear some suggestions on how to approach this issue so it will work? Maybe change the array argument?
You need to create an array of pointers to ints and then pass that. Yes, it's a lot of malloc calls, but it's necessary (since you're using void *).
int main(int argc, char** argv) {
struct List *root;
int i, array_length = argc - 1;
int** array = malloc(sizeof(*array) * array_length);
for (i = 0; i < array_length; i++){
array[i] = malloc(sizeof(*array[i]));
*array[i] = atoi(argv[i + 1]);
}
root = arr2list((void **)array,array_length,cpyElement, destroyElement);
printList(root,echoElement);
freeList(root,destroyElement);
free(array);
return 0;
}
This code:
void destroyElement(void* el) {
if (el != NULL) {
struct List* node = el;
node->next = NULL;
free(node);
}
}
will then need to be changed to (in fact, it only worked before due to a platform-specific bug):
void destroyElement(void* el) {
free(el);
}
Also, do not cast the result of malloc. That means no (int *)malloc(...). Just use malloc(...), it's safer and doesn't cover up errors.
The problem with void * is that while you can freely convert other pointer types to void * and back again and get the original pointer back, you need to do that directly -- you can't pass a void ** where it points at anything other than void *'s and expect it to work.
Even worse, in your case, you're passing an array of int where an array of void * are expected. You can deal with this by casting yout ints to intptr_t and thence to void * to store in your list -- you'll have to do that double-cast back again to get them out again:
void echoElement(void* el) {
printf("%d ", (int)(intptr_t)el);
}
int main(int argc, char** argv) {
int array_length = argc - 1;
void *array = malloc(sizeof(*array) * array_length);
for (int i = 0; i < array_length; i++) {
array[i] = (void *)(intptr_t)atoi(argv[i + 1]);
}
struct List* root = arr2list((void*) array,array_length,cpyElement, destroyElement);
printList(root,echoElement);
I'm attempting to implement open hashing in C using a linked list struct I've already made. The linked list struct works perfectly, however when trying to use them in my hash table struct, I'm constantly given "Segmentation fault (core dumped)"
I've already checked to make sure that I'm using the proper data types and I'm allocating the right amount of memory.
typedef struct LinkedList LinkedList;
LinkedList* createLinkedList(){
LinkedList* rslt = malloc(sizeof(Node*)); //Allocate memory for LL
//rslt->head = calloc(1,sizeof(Node*)); //Allocate memory for head with default Node* value (NULL)
return rslt;
}
void add_end_LinkedList(LinkedList* x, int v){
//Special case: LinkedList is empty
if(x->head == NULL)
x->head = createNode(v);
else{
//Traversing to end of list
Node* p;
for(p = x->head; p->next != NULL; p = p->next){1;}
p->next = createNode(v);
}
}
void add_beg_LinkedList(LinkedList* x, int v){
Node* p;
//Special case: LinkedList is empty
if(x->head == NULL)
x->head = createNode(v);
else{
p = createNode(v);
p->next = x->head;
x->head = p;
}
}
int isIn_LinkedList(LinkedList* x, int v){
for(Node* p = x->head; p != NULL; p = p->next){
if(p->val == v) return 1;
}
return 0;
}
void print_LinkedList(LinkedList* x){
for(Node* p = x->head; p != NULL; p = p->next){
print_Node(p);
printf(", ");
}
printf("\n");
return;
}
//HASHTABLE_____________________________________________________________
struct HashTable{
LinkedList** table;
};
typedef struct HashTable HashTable;
HashTable* createTable(){
HashTable* rslt = {calloc(9,sizeof(LinkedList*))};
for(int i = 9; i < 9; i++)
rslt->table[i] = createLinkedList();
return rslt;
}
int compute_hash(int v){
return v%9;
}
int isIn_HashTable(HashTable* x, int v){
return isIn_LinkedList(x->table[compute_hash(v)], v);
}
int insert_HashTable(HashTable* x, int v){
if(isIn_HashTable(x, v)){
return 0;
}
add_beg_LinkedList(x -> table[compute_hash(v)], v);
return 1;
}
int main(void){
HashTable* a = createTable();
insert_HashTable(a, 6);
return 0;
}
createTable() does not raise any runtime errors. But any other HashTable functions do. I'm not able to access the linked lists in the table.
Rslt is a pointer. You cannot initialize it the way you initialize struts. After returning from the function the the rslt pointer will become invalid in the following code
HashTable* createTable(){
HashTable* rslt = {calloc(9,sizeof(LinkedList*))};
{..} is not a dynamic memory allocation. Try to malloc rslt first
HashTable *rslt = malloc(sizeof(HashTable));
rslt->table = calloc...
I have the following C code:
typedef struct DListNode_ {
void *data;
struct DListNode_ *prev;
struct DListNode_ *next;
} DListNode;
typedef struct DList_ {
int size;
DListNode *tail;
DListNode *head;
} DList;
void insert(DList * list, DListNode * element, int data) {
DListNode * new_element = (DListNode *)malloc(sizeof(DListNode));
new_element->data = &data;
if (list->head==NULL) {
list->head=list->tail=new_element;
list->size++;
return;
}
if(element == NULL) {
// handle size==0?
new_element->next=list->head;
list->head->prev=new_element;
list->head=new_element;
list->size++;
} else {
printf("Not yet implemented!\n");
}
}
void printNodes(DList *list) {
DListNode * pointer = list->head;
if (pointer!=NULL) {
int v= *((int*)pointer->data);
printf("Node has value: %d\n", v);
while (pointer->next != NULL) {
v = *((int*)pointer->data);
printf("Node has value: %d\n", v);
pointer=pointer->next;
}
}
}
int main(int argc, const char * argv[])
{
int e0 = 23;
int e1 = 7;
int e2 = 11;
DList *list = (DList *)malloc(sizeof(DList));
initList(list);
assert(count(list)==0);
insert(list, NULL, e0);
assert(count(list)==1);
insert(list,NULL, e1);
assert(count(list)==2);
insert(list,NULL, e2);
assert(count(list)==3);
printNodes(list);
return 0;
}
I have a few problems:
does DListNode * new_element = (DListNode *)malloc(sizeof(DListNode)); also allocate space for the, data, prev, next pointer or do I manually need to call malloc on each of those pointers?
When I print the content of the data pointer in each node they all have the value 3 even though I insert 23, 7 and 11 and set the data pointer to the address of the int: ** new_element->data = &data;**.
(Introductionary textbooks on C have been ordered)
EDIT:
insert now takes a void pointer to the data:
// Insert data as the new head
void insert(DList *list, DListNode *element, void *data) {
DListNode *new_element = malloc(sizeof(DListNode));
new_element->data = data;
if (list->head==NULL) {
list->head=list->tail=new_element;
list->size++;
return;
}
if(element == NULL) {
new_element->next=list->head;
list->head->prev=new_element;
list->head=new_element;
list->size++;
} else {
printf("Not yet implemented!\n");
}
}
In main I do:
int main(int argc, const char * argv[])
{
int i0=7;
int *ip0 = malloc(sizeof(int));
ip0 = &i0;
int i1=8;
int *ip1 = malloc(sizeof(int));
ip1 = &i1;
int *ip2 = malloc(sizeof(int));
int i2=44;
ip2 = &i2;
DList *list = malloc(sizeof(DList));
initList(list);
// create some nodes
assert(count(list)==0);
insert(list, NULL, ip0);
assert(count(list)==1);
insert(list,NULL, ip1);
assert(count(list)==2);
insert(list,NULL, ip2);
assert(count(list)==3);
printNodes(list);
return 0;
}
which outputs:
Node has value: 44
Node has value: 44
Node has value: 8
but it should be:
Node has value: 44
Node has value: 8
Node has value: 7
malloc(sizeof(DListNode)) allocates space for exactly one DListNode, which by definition consists of a void* and two DListNode pointers. It does not initialize those pointers, though.
You're assigning the address of the data argument to insert. That's a pointer to a temporary which is invalidated once insert returns. The behavior of the program is undefined. The easy solution is to just replace void *data by int data.
You need to manually set those pointers to where they point with malloc. Without it, they will point to a space that isn't of size DListNode.
Don't make the data a pointer. Just make the data an int (it gets auto allocated) and then just set data = data (the data that is passed into insert).
I'm trying to implement sequence_insert_at using the add_to_front function here
Everything before
typedef struct sequence *Sequence;
is pasted from another c file.
void sequence_insert_at(Sequence s, int pos, int item)
{
struct node* temp = s->lst;
for(; pos > 0; --pos)
{
temp = temp->rest;
}
add_to_front(&temp, item);
++s->length;
if(!temp->rest)
{
s->end = temp;
}
//s->lst = temp;
}
I don't know why I keep getting a runtime error. if I clone s->lst and traverse the clone, I'm not modifying the pointer to the node in s, but if I change temp, s->lst should have the reflected changes since the nodes are all linked still. Any ideas as to how to fix this? I tried creating another node that is one before the temp after traversal, and then setting it->rest = temp, but that failed as well.
following mistakes a could spot but only so far to get the main function run
new_sequence does not initialize anything in Sequence it creates. lst is not initialized when you access it in sequence_insert_at
struct node* temp = s->lst;
here how it should look like
Sequence new_sequence()
{
Sequence s = malloc(sizeof(struct sequence));
if(!s)
{
printf("Out of memory. Can't allocate s\n");
exit(EXIT_FAILURE);
}
s->lst = malloc(sizeof(struct node));
if(! s->lst) {
printf("Out of memory. Can't allocate lst\n");
}
s->lst->rest = NULL;
s->length = 0;
return s;
}
also s->lst->rest has to be set to NULL, this is what tells that the list has no more elements an not end witch turns obsolete.
struct sequence
{
struct node* lst;
int length;
};
You should be passing the sequence itself to your functions not a pointer to some internal data in the sequence.
add_to_front(&temp, item);
Your sequence_insert_at function should be the one that can handle any position not add_to_front() so it is easier to call with the position 0 from add_to_front() and your having the the hole work done in one function, not a half here and a half there.
void sequence_insert_at(Sequence s, int pos, int item)
{
if(s && pos <= s->length) {
print_sequence(s);
struct node *newnode = malloc(sizeof(struct node));
if (newnode == NULL) {
printf("ERROR! add_to_front ran out of memory!\n");
exit(EXIT_FAILURE);
}
newnode->first = item;
struct node* temp = s->lst;
struct node* prv = NULL;
for(int i = 0; i < pos; i++) {
printf("skip %d\n", temp->first);
prv = temp;
temp = temp->rest;
}
newnode->rest = temp;
if(pos == 0) {
printf("insert as first\n");
s->lst = newnode;
} else {
printf("insert before %d\n", temp->first);
prv->rest = newnode;
}
++s->length;
}
}
and in add_to_front only one statement is needed
void add_to_front(Sequence s, int item) {
sequence_insert_at(s, 0, item);
}
as for inserting at the back of the list
void add_to_back(Sequence s, int item) {
sequence_insert_at(s, s->length, item);
}
A small test with the main function
void print_sequence(Sequence s)
{
struct node* temp = s->lst;
for(int i = 0; i < s->length; temp = temp->rest) {
printf("%d ", temp->first);
i++;
}
printf("\n");
}
int main()
{
Sequence derp = new_sequence();
sequence_insert_at(derp, 0, 14);
add_to_front(derp, 16);
sequence_insert_at(derp, 0, 17);
sequence_insert_at(derp, 2, 15);
add_to_back(derp, 13);
print_sequence(derp);
delete_sequence(derp);
return 0;
}
output is:
17 16 15 14 13
You'll have to go trough the other functions and fix them.
Finally i should note that variable names you have choosen are little bit confusing if not misleading, i would name them this way
typedef struct node {
int data; /* the data that a node holds */
struct node* next; /* the pointer to the next node */
} Node_t;
typedef struct sequence {
struct node* head; /* head or first element of the sequence/list */
int length; /* length is ok but size is better */
} Sequence_t;