Segmentation Fault with string compare - c

When working with a basic example like this, I am getting a segmentation fault. I believe it's due to the size of the data not being fixed. How can I have variable length data attached to a struct?
struct Node {
char * data;
struct Node* next;
};
void compareWord(struct Node** head_ref, char * new_data) {
if (strcmp((*head_ref)->data, new_data) > 0) {
head_ref->data = new_data;
}
}
int main(int argc, char* argv[]) {
struct Node* head = NULL;
head->data = "abc";
char buf[] = "hello";
compareWord(&head, buf);
return 0;
}

How can I have variable length data attached to a struct?
Answer is - No, you cannot. The reason is the size of the struct should be known at compile time.
The reason for segmentation fault is, your program is accessing head pointer before allocating memory to it:
struct Node* head = NULL;
head->data = "abc";
Allocate memory before using head:
struct Node* head = NULL;
head = malloc (sizeof(struct Node));
if (NULL == head)
exit(EXIT_FAILURE);
head->data = "abc";
Make sure to free allocated memory once you have done with it.
There is something known as Flexible Array Member(FAM) introduced in C99 standard. It may be of your interest.

Related

Problem using free() in a loop creating a linked list from a file

So I have a file called file.txt and i want to create a linked list from the information it contains, where each line of the file is a new node. So far I have this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct sAirport{
char name;
int number;
struct sAirport *next;
}tAirport;
tAirport *createNode(tAirport *newNode, char str[1000]);
void createLinkedList(tAirport **head, tAiport *newNode);
int main()
{
FILE *fa = fopen("test.txt", r);
char str[1000] = {0};
tAirport *head = NULL;
tAirport *newNode = NULL;
while(fgets(str, sizeof(str), fa) != NULL)
{
newNode = createNode(newNode, str);
createLinkedList(&head, newNode);
free(newNode);
newNode = NULL;
}
return 0;
}
tAirport *createNode(tAirport *newNode, char str[1000])
{
char *aux = NULL;
newNode = malloc(sizeof(tAirport));
if(newNode == NULL)
exit(EXIT_FAILURE);
aux = strtok(str, " ");
strcpy(&newNode->name, aux);
aux = strtok(NULL, " ");
sscanf(aux, "%d", &newNode->number);
newNode->next = NULL;
return newNode;
}
void createLinkedList(tAirport **head, tAirport newNode)
{
tAirport *temp = NULL;
if(*head == NULL)
{
*head = newNode;
return;
}
temp = *head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
}
I'm getting weird results and Valgrind says I have lost bytes but I don't know what to do.
Edited so that it can run.
For example the file I'm testing with is:
John 33
Mary 42
Peter 12
What should I do?
Aside from all those warning you will get from compiling this. I just want to tell you that you are misunderstanding how malloc(),free(), and pointer work.
First of all, pointer is just an unsigned long, a natural number just like any other number. The difference is that the pointer store the address of the real memory ( in this case is newNode).
In your program, you malloc() to get your memory, asisgn the memory address to newNode, then you tell your list to hold newNode, finally you free it. So you just free the memory you wish to keep, your list now only hold a bunch of address to freed memory.
Solution for this is, get rid of free() while populating your list, and free them later
The sAirport structure is define the name to be one character. However, from the code, looks like the createNode will allow long name (up to 999 characters). When the createNode create the new entry, the strcpy will overwrite data beyond the allocated space, and will likely cause segmentation fault, or "funny" data.
Consider extending name to the proper size, or using dynamic allocation (malloc) for name.

Freeing a pointer (to a void*) inside of a struct

C newbie here, and I can't seem to figure this one out. So I'm starting to implement a linked-list (just something basic so I can wrap my head around it) and I've hit a snag. The program runs fine, but I can't free() the data stored in my struct.
Here's the source:
#include <stdio.h>
#include <stdlib.h>
struct node {
struct node* next;
void* data;
size_t data_size;
};
typedef struct node node;
node* create_node(void* data, size_t size)
{
node* new_node = (node*)malloc(sizeof(node));
new_node->data = (void*)malloc(size);
new_node->data = data;
new_node->next = NULL;
return new_node;
}
void destroy_node(node** node)
{
if(node != NULL)
{
free((*node)->next);
//this line here causes the error
free((*node)->data);
free(*node);
*node = NULL;
printf("%s\n", "Node destroyed!");
}
}
int main(int argc, char const *argv[])
{
float f = 4.325;
node *n;
n = create_node(&f, sizeof(f));
printf("%f\n", *((float*)n->data));
if (n->next == NULL)
printf("%s\n", "No next!");
destroy_node(&n);
return 0;
}
I get this message in the program output:
malloc: *** error for object 0x7fff5b4b1cac: pointer being freed was not allocated
I'm not entirely keen on how this can be dealt with.
This is because when you do:
new_node->data = data;
you replaces the value put by malloc just the line before.
What you need is to copy the data, see the function memcpy
node* create_node(void* data, size_t size)
...
new_node->data = (void*)malloc(size);
new_node->data = data;
Here, (1) you are losing memory given by malloc because the second assignment replaces the address (2) storing a pointer of unknown origin.
Number two is important because you can't guarantee that the memory pointed to by data was actually malloced. This causes problems when freeing the data member in destroy_node. (In the given example, an address from the stack is being freed)
To fix it replace the second assignment with
memcpy (new_node->data, data, size);
You also have a potential double free in the destroy_node function because the next member is also being freed.
In a linked list, usually a node is freed after being unlinked from the list, thus the next node shouldn't be freed because it's still reachable from the predecessor of the node being unlinked.
While you got an answer for the immediate problem, there are numerous other issues with the code.
struct node {
struct node* next;
void* data;
What's up with putting * next to type name? You are using it inconsistently anyway as in main you got node *n.
size_t data_size;
};
typedef struct node node;
node* create_node(void* data, size_t size)
{
node* new_node = (node*)malloc(sizeof(node));
What are you casting malloc for? It is actively harmful. You should have used sizeof(*new_node). How about checking for NULL?
new_node->data = (void*)malloc(size);
This is even more unnecessary since malloc returns void * so no casts are necessary.
new_node->data = data;
The bug already mentioned.
new_node->next = NULL;
return new_node;
}
void destroy_node(node** node)
{
if(node != NULL)
{
How about:
if (node == NULL)
return;
And suddenly you get rid of indenation for the entire function.
free((*node)->next);
//this line here causes the error
free((*node)->data);
free(*node);
*node = NULL;
printf("%s\n", "Node destroyed!");
What's up with %s instead of mere printf("Node destroyed!\n")? This message is bad anyway since it does not even print an address of aforementioned node.

C - Unable to free memory allocated within a linked list structure

Consider the following code snippet
struct node {
char *name;
int m1;
struct node *next;
};
struct node* head = 0; //start with NULL list
void addRecord(const char *pName, int ms1)
{
struct node* newNode = (struct node*) malloc(sizeof(struct node)); // allocate node
int nameLength = tStrlen(pName);
newNode->name = (char *) malloc(nameLength);
tStrcpy(newNode->name, pName);
newNode->m1 = ms1;
newNode->next = head; // link the old list off the new node
head = newNode;
}
void clear(void)
{
struct node* current = head;
struct node* next;
while (current != 0)
{
next = current->next; // note the next pointer
/* if(current->name !=0)
{
free(current->name);
}
*/
if(current !=0 )
{
free(current); // delete the node
}
current = next; // advance to the next node
}
head = 0;
}
Question:
I am not able to free current->name, only when i comment the freeing of name, program works.
If I uncomment the free part of current->name, I get Heap corruption error in my visual studio window.
How can I free name ?
Reply:
#all,YES, there were typos in struct declaration. Should have been char* name, and struct node* next. Looks like the stackoverflow editor took away those two stars.
The issue was resolved by doing a malloc(nameLength + 1).
However,If I try running the old code (malloc(namelength)) on command prompt and not on visual studio, it runs fine.
Looks like, there are certain compilers doing strict checking.
One thing that I still do not understand is , that free does not need a NULL termination pointer, and chances to overwrite the allocated pointer is very minimal here.
user2531639 aka Neeraj
This is writing beyond the end of the allocated memory as there is no space for the null terminating character, causing undefined behaviour:
newNode->name = (char *) malloc(nameLength);
tStrcpy(newNode->name, pName);
To correct:
newNode->name = malloc(nameLength + 1);
if (newNode->name)
{
tStrcpy(newNode->name, pName);
}
Note calling free() with a NULL pointer is safe so checking for NULL prior to invoking it is superfluous:
free(current->name);
free(current);
Additionally, I assume there are typos in the posted struct definition (as types of name and next should be pointers):
struct node {
char* name;
int m1;
struct node* next;
};

linked list behavior - help me understand

i am in the process of learning linked lists, and i dont understand the behavior change when freeing a string. Here is the code:
#include <stdio.h>
#include <stdlib.h>
struct node {
char* data;
struct node* next;
};
void Push(struct node** headRef, char *data)
{
struct node* newNode = malloc(sizeof(struct node));
newNode->data = data;
newNode->next = *headRef; // The '*' to dereferences back to the real head
*headRef = newNode; // ditto
}
int main(int argc, const char * argv[])
{
char* auxStr;
struct node* list;
struct node* auxPtr;
int i=5;
while (i<9)
{
auxStr=malloc(sizeof("String:%d"));
sprintf(auxStr, "String:%d",i);
Push(&list, auxStr);
i++;
}
auxPtr=list;
i=0;
while (auxPtr)
{
printf("Node:%d - Data:%s\n",i++,auxPtr->data);
auxPtr=auxPtr->next;
}
return 0;
}
That results in:
Node:0 - Data:String:8
Node:1 - Data:String:7
Node:2 - Data:String:6
Node:3 - Data:String:5
now, when i add free(auxStr) in the first while:
while (i<9)
{
auxStr=malloc(sizeof("String:%d"));
sprintf(auxStr, "String:%d",i);
Push(&list, auxStr);
free(auxStr);
i++;
}
i now get:
Node:0 - Data:String:8
Node:1 - Data:String:8
Node:2 - Data:String:8
Node:3 - Data:String:8
Can someone explain why ? i know it may not be the most efficient code freeing in there multiple times, but i saw this behavio and it is puzzling me. Would appreciate your help to help me understand the concept better.
Thanks
You are getting undefined behavior.
You are freeing a memory (auxPtr) but you still happen to have a pointer to it - as the data in the relevant node. That is called a dangling reference.
What happens with this data is undefined, and it happens to be reusing the same address for each new allocation (but again, anything can happen).
Thus, when later printing the data - the output is undefined.
You aren't copying the data string by strncpy - instead you are simply assigning pointer to the same string that you free later
As indicated here acessing a poitner after you free it is undefined behavior.
Each of your data in struct node points on the same address. When freeing auxPtr, you are accessing to a memory location which is not allocated anymore. In C, it leads to an undefined behavior. It could be a better idea to dynamically allocate your data, as follow.
#include <assert.h>
#include <stdlib.h>
#include <string.h>
void Push(struct node **head, const char *data, size_t size)
{
struct node *elt;
elt = malloc(sizeof *elt);
assert(elt != NULL);
elt->data = malloc(size);
assert(elt->data != NULL);
memcpy(elt->data, data, size);
elt->next = *head;
*head = elt;
}
Moreover, there is no null pointer in your list. You should allocate list first.

segfault with linked list

I am having trouble with linked lists in C, I have only done data structures such as this in c++.
Gdb is giving me a
Program received signal SIGSEGV, Segmentation fault.
0x0804a23c in addArg (base=0x1, argument=0x804e410 "is") at myshell.c:42
42 while ( (curr != NULL) && (curr->n != NULL) )
I am familiar with segmentation faults having to do with memory, however I thought I have allocated memory correctly. What am I doing wrong?
addArg is being called as addArg(currentCmd->args, lexeme);and currentCmd is a pointer to a node struct
struct lnode {
char *x;
struct lnode *n;
};
struct node
{
char *command;
struct lnode *args;
int input;
int output;
int error;
char *in;
char *out;
char *err;
struct node *next;
struct node *prev;
};
void addArg(struct lnode *base, char *argument)
{
struct lnode *curr = base;
//this is line 42
while ( (curr != NULL) && (curr->n != NULL) )
curr = curr->n;
curr -> n = malloc(sizeof(struct lnode));
curr = curr->n;
curr->x = strdup(argument);
curr->n = NULL;
}
struct node* createNode(char *command_, int input_, int output_, int error_, char *in_, char *out_, char *err_, struct node *prev_)
{
struct node *n;
n = malloc(sizeof (struct node));
n->command = strdup(command_);
n->prev = prev_;
n->next = NULL;
n->input = input_;
n->output = output_;
n->error = error_;
n->in = in_;
n->out = out_;
n->err = err_;
n->args=malloc(sizeof(struct lnode));
return n;
}
It looks like currentCmd->args is an invalid pointer. Perhaps a pointer to free()d memory. Or an uninitialized pointer, or a pointer to a local variable that's gone out of scope (though these latter two don't appear to be the case here).
Or perhaps you've accidentally overwritten out-of-bounds memory somewhere else in your program. Pointer issues aren't always at the point of failure; sometimes they're in earlier code, unrelated code even.
I solved this issue by making the lnode *args into lnode args and making the required changes to memory managment.
What i can see from your gdb output, the problem with while ( (curr != NULL) && (curr->n != NULL) ) is that if curr == NULL you are still trying to access curr->n to compare, so you should change that condition to only compare curr, and handle curr->n only if curr is not null, maybe breaking the cicle inmediatly if curr->n == NULL.

Resources