Chain List, story of pointers - c

I have this following code:
void pushInList(t_chan **chan, char *name, char *nick_user)
{
t_chan *new_channel;
(void)nick_user;
if ((new_channel = malloc(sizeof(t_chan))) == NULL)
return ;
new_channel->name = name;
new_channel->prev = (*chan);
(*chan) = new_channel;
}
display_list(t_chan *chan, int fd)
{
int i;
i = 0;
while (chan != NULL)
{
printf("list : %s\n", chan->name);
chan = chan->prev;
}
}
int create_chanel(int fd, char *buffer, t_chan **chan)
{
char *tmp;
int i;
i = 0;
if ((tmp = get_param(fd, buffer, 2, "NICK")) == NULL)
return (EXIT_FAILURE);
while ((*chan) != NULL)
{
/* FUTUR CHECK OF EXISTING CHANEL*/
(*chan) = (*chan)->prev;
}
if ((*chan) == NULL)
pushInList(chan, tmp, "Kilian");
return (EXIT_SUCCESS);
}
int main()
{
t_chan *chan;
char *test;
chan = NULL;
test = strdup("JOIN Coucou");
create_chanel(4, test, &chan);
test = strdup("JOIN Google");
create_chanel(4, test, &chan);
printf("-------------------\nlast display :\n");
display_list(chan, 4);
}
I don't understand why my list is every time NULL. I passed a pointer but in my main the list don't keep its values.
Can you help me, I don't understand...
It's a chain list of channel, When a client send "Join Coucou", if the channel Coucou doesn't exist I create a new node.
Thank you in advance,
Cordialy

Related

Manipulating structs with a void function in C

so I've been set a task of creating a faux string struct and implementing all the usual string functions on my faux string struct. I'm stuck on the tests of my strcat implementation called append, with the first test failing (segfault) being the 5th line. My function for creating new structs should be OK because it passed all the tests, but I've included it just incase.
I've already been able to successfully implement length, get, set and copy functions for my faux string structs.
The struct:
struct text {
int capacity;
char *content;
};
typedef struct text text;
My function for creating new structs:
text *newText(char *s) {
printf("new Text from %s\n", s);
int sizeNeeded = (strlen(s)+1);
int sizeGot = 24;
while (sizeNeeded > sizeGot) {
sizeGot = sizeGot * 2;
}
text *out = malloc(sizeGot);
char *c = malloc(sizeGot);
strcpy(c, s);
out->content = c;
out->capacity = (sizeGot);
printf("the capacity is %d\n", sizeGot);
return out;
free(c);
}
My append function:
void append(text *t1, text *t2) {
printf("t1 content is %s, t2 content is %d\n", t1->content, *t2->content);
int sizeNeeded = (t1->capacity + t2->capacity);
int sizeGot = 24;
while (sizeNeeded > sizeGot) {
sizeGot = sizeGot * 2;
}
char *stringy = calloc(sizeGot, 32);
stringy = strcat(t1->content, t2->content);
free(t1);
t1 = newText(stringy);
}
and finally the tests:
void testAppend() {
text *t = newText("car");
text *t2 = newText("pet");
append(t, t2);
assert(like(t, "carpet"));
assert(t->capacity == 24);
text *t3 = newText("789012345678901234");
append(t, t3);
assert(like(t, "carpet789012345678901234"));
assert(t->capacity == 48);
freeText(t);
freeText(t2);
freeText(t3);
}
You are allocating memory in the wrong way. You could fix this by using a flexible array member like this:
typedef struct {
int capacity;
char content[];
} text;
text *out = malloc(sizeof(text) + sizeof(something));
strcpy(out->content, str);
...
And obviously code such as this is nonsense:
return out;
free(c);
}
Enable compiler warnings and listen to them.
Och, some errors you have:
Inside text_new you allocate memory for text *out using text *out = malloc(sizeGot); when sizeGot = 24 is a constant value. You should allocate sizeof(*out) or sizeof(text) bytes of memory for it.
I don't know what for int sizeGot = 24; while (sizeNeeded > sizeGot) the loop inside text_new and append is for. I guess the intention is to do allocations in power of 24. Also it mostly looks like the same code is in both functions, it does look like code duplication, which is a bad thing.
Inside append You pass a pointer to t1, not a double pointer, so if you modify the t1 pointer itself the modification will not be visible outside of function scope. t1 = newText(stringy); is just pointless and leaks memory. You could void append(text **t1, text *t2) and then *t1 = newText(stringy). But you can use a way better approach using realloc - I would expect append to "append" the string, not to create a new object. So first resize the buffer using realloc then strcat(&t1->content[oldcapacity - 1], string_to_copy_into_t1).
int sizeNeeded = (t1->capacity + t2->capacity); is off. You allocate capacity in power of 24, which does not really interact with string length. You need to have strlen(t1->content) + strlen(t2->content) + 1 bytes for both strings and the null terminator.
Try this:
size_t text_newsize(size_t sizeNeeded)
{
// I think this is just `return 24 << (sizeNeeded / 24);`, but not sure
int sizeGot = 24;
while (sizeNeeded > sizeGot) {
sizeGot *= 2;
}
return sizeGot;
}
text *newText(char *s) {
printf("new Text from %s\n", s);
if (s == NULL) return NULL;
int sizeNeeded = strlen(s) + 1;
int sizeGot = text_newsize(sizeNeeded);
text *out = malloc(sizeof(*out));
if (out == NULL) {
return NULL;
}
out->content = malloc(sizeGot);
if (out->content == NULL) {
free(out);
return NULL;
}
strcpy(out->content, s);
out->capacity = sizeGot;
printf("the capacity is %d\n", sizeGot);
return out;
}
and this:
int append(text *t1, text *t2) {
printf("t1 content is %s, t2 content is %s\n", t1->content, t2->content);
int sizeNeeded = strlen(t1->content) + strlen(t2->content) + 1;
if (t1->capacity < sizeNeeded) {
// this could a text_resize(text*, size_t) function
int sizeGot = text_newsize(sizeNeeded);
void *tmp = realloc(t1->content, sizeGot);
if (tmp == NULL) return -ENOMEM;
t1->content = tmp;
t1->capacity = sizeGot;
}
strcat(t1->content, t2->content);
return 0;
}
Some remarks:
Try to handle errors in your library. If you have a function like void append(text *t1, text *t2) let it be int append(text *t1, text *t2) and return 0 on success and negative number on *alloc errors.
Store the size of everything using size_t type. It's defined in stddef.h and should be used to represent a size of an object. strlen returns size_t and sizeof also returns size_t.
I like to put everything inside a single "namespace", I do that by prepending the functions with a string like text_.
I got some free time and decided to implement your library. Below is the code with a simple text object storing strings, I use 24 magic number as allocation chunk size.
// text.h file
#ifndef TEXT_H_
#define TEXT_H_
#include <stddef.h>
#include <stdbool.h>
struct text;
typedef struct text text;
text *text_new(const char content[]);
void text_free(text *t);
int text_resize(text *t, size_t newsize);
int text_append(text *to, const text *from);
int text_append_mem(text *to, const void *from, size_t from_len);
const char *text_get(const text *t);
int text_append_str(text *to, const char *from);
char *text_get_nonconst(text *t);
size_t text_getCapacity(const text *t);
bool text_equal(const text *t1, const text *t2);
#endif // TEXT_H_
// text.c file
//#include "text.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
struct text {
size_t capacity;
char *content;
};
text *text_new(const char content[])
{
text * const t = malloc(sizeof(*t));
if (t == NULL) goto MALLOC_ERR;
const struct text zero = {
.capacity = 0,
.content = NULL,
};
*t = zero;
if (content != NULL) {
const int ret = text_append_str(t, content);
if (ret) {
goto TEXT_APPEND_ERR;
}
}
return t;
TEXT_APPEND_ERR:
free(t);
MALLOC_ERR:
return NULL;
}
void text_free(text *t)
{
assert(t != NULL);
free(t->content);
free(t);
}
int text_resize(text *t, size_t newcapacity)
{
// printf("%s %d -> %d\n", __func__, t->capacity, newcapacity);
// we resize in chunks
const size_t chunksize = 24;
// clap the capacity into multiple of 24
newcapacity = (newcapacity + chunksize - 1) / chunksize * chunksize;
void * const tmp = realloc(t->content, newcapacity);
if (tmp == NULL) return -ENOMEM;
t->content = tmp;
t->capacity = newcapacity;
return 0;
}
int text_append_mem(text *to, const void *from, size_t from_len)
{
if (to == NULL || from == NULL) return -EINVAL;
if (from_len == 0) return 0;
const size_t oldcapacity = to->capacity == 0 ? 0 : strlen(to->content);
const size_t newcapacity = oldcapacity + from_len + 1;
int ret = text_resize(to, newcapacity);
if (ret) return ret;
memcpy(&to->content[newcapacity - from_len - 1], from, from_len);
to->content[newcapacity - 1] = '\0';
return 0;
}
int text_append_str(text *to, const char *from)
{
if (to == NULL || from == NULL) return -EINVAL;
return text_append_mem(to, from, strlen(from));
}
int text_append(text *to, const text *from)
{
if (to == NULL || from == NULL) return -EINVAL;
if (text_getCapacity(from) == 0) return 0;
return text_append_str(to, text_get(from));
}
const char *text_get(const text *t)
{
return t->content;
}
const size_t text_strlen(const text *t)
{
return t->capacity == 0 ? 0 : strlen(t->content);
}
size_t text_getCapacity(const text *t)
{
return t->capacity;
}
bool text_equal_str(const text *t, const char *str)
{
assert(t != NULL);
if (str == NULL && t->capacity == 0) return true;
const size_t strlength = strlen(str);
const size_t t_strlen = text_strlen(t);
if (t_strlen != strlength) return false;
if (memcmp(text_get(t), str, strlength) != 0) return false;
return true;
}
// main.c file
#include <stdio.h>
int text_testAppend(void) {
text *t = text_new("car");
if (t == NULL) return -1;
text *t2 = text_new("pet");
if (t2 == NULL) return -1;
if (text_append(t, t2)) return -1;
assert(text_equal_str(t, "carpet"));
assert(text_getCapacity(t) == 24);
text *t3 = text_new("789012345678901234");
if (t3 == NULL) return -1;
if (text_append(t, t3)) return -1;
assert(text_equal_str(t, "carpet789012345678901234"));
assert(text_getCapacity(t) == 48);
text_free(t);
text_free(t2);
text_free(t3);
return 0;
}
int main()
{
text *t1 = text_new("abc");
text_append_str(t1, "def");
printf("%s\n", text_get(t1));
text_free(t1);
printf("text_testAppend = %d\n", text_testAppend());
return 0;
}

Designing a generic hash

I am trying to implement a generic hash structure that can support any type of data and any hash function.
A wrote the code and try to run it, it dosn't work, it breaks. I try to debug it and there it works well. I don't know where the problem is?
Here is the code that I used for implementing the structure:
The "hash.h" file:
typedef struct tip_hash_nod
{
void *info;
struct tip_hash_nod *urm;
}NOD_LISTA_HASH;
typedef struct
{
NOD_LISTA_HASH *Table;
int size;
int sizeMemory;
int (*hash)(const void *obiect,const int m);
void (*distruge)(void *obiect);
}*HASH;
void initializare_hash(HASH *h,int size,int (*hash_dat)(const void *obiect,const int m),void (*distruge)(void *obiect));
int hash_insert(HASH *h,void *obiect,int sizeOfObiect);
int hash_search(HASH h,void *obiect,int (*compara)(const void *a,const void *b));
void hash_delete(HASH *h);
And the "hash.c" file:
void initializare_hash(HASH *h,int size,int (*hash_dat)(const void *obiect,const int m),void (*distruge)(void *obiect))
{
int i;
(*h) = (HASH)malloc(sizeof(HASH));
(*h)->sizeMemory = size;
if(size != 0)
{
(*h)->Table = (NOD_LISTA_HASH *)malloc((*h)->sizeMemory * sizeof(NOD_LISTA_HASH));
for(i=0;i<(*h)->sizeMemory;i++)
{
(*h)->Table[i].info = NULL;
(*h)->Table[0].urm = NULL;
}
}
else
{
(*h)->Table = (NOD_LISTA_HASH *)malloc(sizeof(NOD_LISTA_HASH));
(*h)->Table[0].info = NULL;
(*h)->Table[0].urm = NULL;
(*h)->sizeMemory = 1;
}
(*h)->size = 0;
(*h)->hash = hash_dat;
(*h)->distruge = distruge;
}
int hash_insert(HASH *h,void *obiect,int sizeOfObiect)
{
int i,poz;
NOD_LISTA_HASH *p;
if((*h)->size == (*h)->sizeMemory)
{
HASH h1;
initializare_hash(&h1,2*(*h)->sizeMemory,(*h)->hash,(*h)->distruge);
for(i=0;i<(*h)->sizeMemory;i++)
{
if((*h)->Table[i].info != NULL)
hash_insert(&h1,(*h)->Table[i].info,sizeOfObiect);
p=(*h)->Table[i].urm;
while(p!=NULL)
{
hash_insert(&h1,p->info,sizeOfObiect);
p = p->urm;
}
}
hash_delete(h);
*h=h1;
return hash_insert(h,obiect,sizeOfObiect);
}
else
{
poz = (*h)->hash(obiect,(*h)->sizeMemory);
if((*h)->Table[poz].info == NULL)
{
(*h)->Table[poz].info = malloc(sizeOfObiect);
memcpy((*h)->Table[poz].info,obiect,sizeOfObiect);
(*h)->Table[poz].urm = NULL;
(*h)->size++;
}
else
{
p = &((*h)->Table[poz]);
while(p->urm!=NULL)
p = p->urm;
p->urm = (NOD_LISTA_HASH *)malloc(sizeof(NOD_LISTA_HASH));
p = p->urm;
p->info = malloc(sizeOfObiect);
memcpy(p->info,obiect,sizeOfObiect);
p->urm = NULL;
}
return poz;
}
}
int hash_search(HASH h,void *obiect,int (*compara)(const void *a,const void *b))
{
int poz;
NOD_LISTA_HASH *p;
poz = h->hash(obiect,h->sizeMemory);
if(h->Table[poz].info == NULL)
return -1;
else
if(compara(h->Table[poz].info,obiect)==0)
return poz;
else
{
p=h->Table[poz].urm;
while(p != NULL)
{
if(compara(p->info,obiect)==0)
return poz;
p = p->urm;
}
return -1;
}
}
static void distruge_lista(NOD_LISTA_HASH *p,void (*distruge_obiect)(void *obiect))
{
if(p->urm != NULL)
distruge_lista(p->urm,distruge_obiect);
else
{
if(p->info != NULL)
distruge_obiect(p->info);
free(p);
}
}
void hash_delete(HASH *h)
{
int i;
for(i=0;i<(*h)->sizeMemory;i++)
{
if((*h)->Table[i].info != NULL && (*h)->Table[i].urm != NULL)
{
distruge_lista((*h)->Table[i].urm,(*h)->distruge);
}
}
free((*h)->Table);
*h = NULL;
}
And this is my "main.c" file:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include "hash.h"
int comparare(const void *a,const void *b)
{
return (*(int *)a - *(int *)b);
}
int hash(const void *obiect,int m)
{
return (*(int *)obiect) % m;
}
void distruge_obiect(void *obiect)
{
free((int *)obiect);
}
int main()
{
HASH h;
int val,error;
initializare_hash(&h,0,hash,distruge_obiect);
val = 20;
hash_insert(&h,&val,sizeof(int));
val = 800;
hash_insert(&h,&val,sizeof(int));
val = 2000;
hash_insert(&h,&val,sizeof(int));
val = 765;
hash_insert(&h,&val,sizeof(int));
val = 800;
error = hash_search(h,&val,comparare);
if(error == -1)
printf("Elementul %d nu se afla in hash.\n",val);
else
printf("Elementul %d se afla pe pozitia: %d.\n",val,error);
hash_delete(&h);
getch();
return 0;
}
How I already sad if I try to debug it works with no problem, but when I run it, it crashes. I can onely make an assumption that it can not dealocate the memory or something. My call stack loocks like this:
You've dropped a pretty big pile of code on us, without much to go on. I had a quick look anyway, and noticed this incorrect allocation:
(*h) = (HASH)malloc(sizeof(HASH));
HASH is a pointer type, so you are allocating only enough memory for one pointer. You want to allocate memory for the thing to which it points:
*h = malloc(sizeof(**h));
(The cast is not required in C, and some folks around here will be strident about not using one.)
That error would be entirely enough to cause all manner of bad behavior. In particular, the erroneous code might seem to work until you dynamically allocate more memory and write to that, so perhaps that explains why your tests crash on the second insertion.

Parsing a read in file and storing it in a binary tree

I am getting a segfault when I try to insert my node into the binary tree. I run the program with gdb and here is what I find out about the segfault, but I dont really know what to change in my insert and create function. Thanks for the help in advance.
Program received signal SIGSEGV, Segmentation fault.
__strcmp_sse42 () at ../sysdeps/x86_64/multiarch/strcmp.S:260
260 movdqu (%rsi), %xmm2
(gdb) where
#0 __strcmp_sse42 () at ../sysdeps/x86_64/multiarch/strcmp.S:260
#1 0x0000000000400a42 in insert_into_commands_tree (node=0x7fffffffe0b0,
data=0x602270) at lab8.c:116
#2 0x00000000004009d7 in create_commands_tree (commands=0x7fffffffe0b0,
file=0x7fffffffe4a1 "commands.dat") at lab8.c:104
#3 0x0000000000400835 in main (argc=2, argv=0x7fffffffe1b8) at lab8.c:48
What my program does is reads in a text file and parses the strings, then it stores them into a binary tree. Then the user types in a command and I search the tree and see if the command is listed in the tree. I am going to post my full code so you all can see it, then post the file I read in and the sample output, and hopefully someone can help me with this segfault error. Thanks a lot in advance. My teacher provided us with the main and tokenizer function too.
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#define COMMAND_NAME_LEN 50
#define MAX_SPLIT_SIZE 50
#define MAX_BUFF_SIZE 50
typedef struct Command_ {
char name[COMMAND_NAME_LEN];
int expected_param_count;
struct Command_ *left;
struct Command_ *right;
}Command;
typedef struct StringArray_ {
char **strings;
int size;
}StringArray;
StringArray* tokenizer (char *string, const char* delimiters);
void free_string_array(StringArray *sr);
void create_commands_tree(Command **commands, const char *file);
void insert_into_commands_tree(Command** node, char** data);
Command* get_command(Command *node, const char *command);
Command* create_command(char **data);
void destroy_commands_tree(Command* node);
void display_commands(Command *node);
int main (int argc, char *argv[]) {
if (argc < 2) {
printf("%s is missing commands.dat\n", argv[0]);
return 0;
}
Command* options = NULL;
create_commands_tree(&options,argv[1]);
int checking = 1;
char input_buffer[MAX_BUFF_SIZE];
do {
printf("Command: ");
fgets(input_buffer,MAX_BUFF_SIZE,stdin);
StringArray* parsed_input = tokenizer(input_buffer," \n");
Command* c = get_command(options,parsed_input->strings[0]);
if( c && parsed_input->size == c->expected_param_count) {
if (strcmp(c->name, "quit") == 0){
checking = 0;
}
printf("Valid command used\n");
}
else {
printf("Invalid command, please try again\n");
}
free_string_array(parsed_input);
}while (checking);
destroy_commands_tree(options);
}
void create_commands_tree(Command **commands, const char *file) {
FILE *input;
input = fopen(file, "r");
char strings[100];
StringArray *temp2;
while(fgets(strings,100,input)){
temp2 = tokenizer(strings, "\n");
insert_into_commands_tree(commands,temp2->strings);
}
}
void insert_into_commands_tree(Command** node, char** data) {
if(*node == NULL){
*node = create_command(data);
}
else if( *node != NULL){
if(strcmp(data[0],(*node)->name) < 0)
insert_into_commands_tree(&(*node)->left,data);
else if(strcmp(data[0], (*node)->name) > 0)
insert_into_commands_tree(&(*node)->right,data);
}
}
Command* create_command(char **data) {
Command* new_;
new_ = (Command*)malloc(sizeof(Command));
strncpy(new_->name, data[0], COMMAND_NAME_LEN);
new_->expected_param_count = atoi(data[1]);
new_->right = NULL;
new_->left = NULL;
return new_;
}
Command* get_command(Command *node, const char *command) {
Command *temp = node;
int compare;
if(temp){
compare = strcmp(node->name, command);
if(compare == 0){
return temp;
}
else if(compare < 0){
return (get_command(node->right, command));
}
else{
if(compare > 0){
return (get_command(node->left, command));
}}
}
return temp;
}
void destroy_commands_tree(Command* node) {
if( node == NULL){
return;
}
destroy_commands_tree(node->left);
destroy_commands_tree(node->right);
free(node);
}
void display_commands(Command *node) {
printf("\npickup <item>");
printf("\nhelp ");
printf("\nquit ");
printf("\nload <file>\n\n");
}
StringArray* tokenizer (char *string, const char* delimiters){
StringArray* sr = malloc(sizeof(StringArray));
sr->strings = malloc(MAX_SPLIT_SIZE * sizeof(char *));
size_t len;
char* hold;
(sr->strings)[0] = malloc(MAX_BUFF_SIZE * sizeof(char));
hold = strtok(string, delimiters);
int i;
for(i = 1; i < MAX_SPLIT_SIZE; i++){
hold = strtok(NULL, delimiters);
if(hold == NULL){
sr->size = i + 1;
break;
}
(sr->strings)[i] = malloc(MAX_BUFF_SIZE * sizeof(char));
strcpy((sr->strings)[i], hold);
}
return sr;
}
void free_string_array(StringArray *sr) {
int i;
for(i = 0; i < sr->size; ++i){
free(sr->strings[i]);
}
free(sr->strings);
free(sr);
}
Here is the sample output that was given:
]$ ./a.out commands.dat 
Command: pickup 
Invalid command, please try again 
Command: pickup ball 
Valid command used 
Command: quit 1 
Invalid command, please try again 
Command: load 
Invalid command, please try again 
Command: load bak.sav 
Valid command used 
Command: help
Valid command used
Command: help 2 
Invalid command, please try again 
Command: quit 
Valid command used 
And the file that we read in is as follows:
pickup,2
help,1
quit,1
load,2
There are several issues with this code:
In function insert_into_commands_tree
Like said in a comment above, the condition should be if (*node == NULL). This is probably what caused a segfault.
Furthermore, the if ... else if structure is a bit redundant here, since it is a true/false condition. You can simply use:
void insert_into_commands_tree(Command** node, char** data) {
if(*node == NULL) {
*node = create_command(data);
}
else {
if(strcmp(data[0],(*node)->name) < 0)
insert_into_commands_tree(&(*node)->left,data);
else if(strcmp(data[0], (*node)->name) > 0)
insert_into_commands_tree(&(*node)->right,data);
}
}
(but it's just a small detail)
In function create_commands_tree
What you do here is read a line of the input file with fgets, and separate this line with the toker "\n", which is useless (since fgets already separates the lines). I think you meant:
temp2 = tokenizer(strings, ",");
In function tokenizer
The output of this function is not what it should be. The main issue here is that you don't copy the first token into your StringArray. Below is a valid (and a bit simplified) tokenizer function:
StringArray* tokenizer (char *string, const char* delimiters)
{
StringArray* sr = malloc(sizeof(StringArray));
sr->strings = malloc(MAX_SPLIT_SIZE * sizeof(char *));
char* hold;
int i = 0;
hold = strtok(string, delimiters);
while ((hold != NULL) && (i < MAX_SPLIT_SIZE))
{
(sr->strings)[i] = malloc(MAX_BUFF_SIZE * sizeof(char));
strncpy((sr->strings)[i], hold, MAX_SPLIT_SIZE);
i++;
hold = strtok(NULL, delimiters);
}
sr->size = i;
return sr;
}
With these modifications, your code seems to do what you expect.

Memory allocation and core dump for pointers to structures in c

Sorry I'm new to memory allocation and structure (so most probably it's some silly thing I've missed). I've got the following code which is core dumping on Solaris. I'm not also sure how to add more elements later (should I realloc memory?)
enum field_type
{
FLD_STRING,
FLD_SHORT
};
typedef struct {
long id;
char *name;
field_type type;
void *value;
} myStruct_t ;
typedef struct {
long id;
const char *name;
field_type type;
const char *descr;
} myStructDef_t;
myStructDef_t Alldef[] =
{
{0, "FirstField", FLD_STRING, "First Field Of Structure"},
{1, "SecondField", FLD_STRING, "Second Field Of Structure"},
{-1}
};
int main()
{
myStruct_t *p_struct;
char tmp[100] = {'\0'};
long id = 0;
if(NULL == (p_struct= structAlloc(1024)))
{
print("Failed allocating memory\n");
return 0;
}
sprintf(tmp, "Test Adding value");
addValueToStruct(p_struct, id, (void *)tmp);
}
myStruct_t *structAlloc(long size)
{
myStruct_t *tmp = (myStruct_t *) calloc(size, sizeof *tmp);
if(NULL != tmp)
tmp->id = -1;
return tmp;
}
int addValueToStruct(myStruct_t *p_struct, long id, (void *)value)
{
myStruct_t *bkStruct = p_struct;
myStructDef_t *def = NULL;
if(-1 == getIdDefinition(def, id))
{
printf("Failed to find definition for id [%ld]", id);
return -1;
}
// Core dumping on 1st line below
bkStruct->id = def->id;
sprintf(bkStruct->name, "%s", def->name);
bkStruct->type = def->def->type;
if(FLD_SHORT == bkStruct->type)
memcpy(bkStruct->value, value, sizeof(*(short *)value));
else if(FLD_STRING == bkStruct->type)
memcpy(bkStruct->value, value, sizeof(*(char *)value));
return 0;
}
int getIdDefinition(myStructDef_t *def, long id)
{
myStructDef_t *AllDefsTmp = Alldef;
bool found = false;
while( -1 != AllDefsTmp->id)
{
if(id == AllDefsTmp->id)
{
def = AllDefsTmp;
found = true;
break;
}
AllDefsTmp ++;
}
if(!found)
return -1;
return 0;
}
Thanks :)
myStructDef_t *def = NULL;
if(-1 == getIdDefinition(def, id))
{
printf("Failed to find definition for id [%ld]", id);
return -1;
}
// Core dumping on 1st line below
bkStruct->id = def->id;
Calling GetIdDefinition(def, id) will fill in def within the that function, but won't change the value within the addValueToStruct function - you need a double pointer (in C) or reference (in C++), so that you can change the value of def itself. (Or you could of course just return the value you found, instead of -1 or 0 return value).

having trouble with storing string in linked list

I am having trouble storing a string in a linked list. This is the function that inserts a node to the list:
void insert_rec(rec_ptr *h_ptr, rec_ptr *t_ptr, int a, int b, int c, char* cs)
{
rec_ptr new_ptr;
new_ptr = rec_ptr( malloc( sizeof(REC) ) );
if(new_ptr != NULL)
{
new_ptr->x = a;
new_ptr->y = b;
new_ptr->z = c;
new_ptr->c = cs;
new_ptr->next = NULL;
if(*h_ptr == NULL){
*h_ptr = new_ptr;
}
else{
(*t_ptr)->next = new_ptr;
}
*t_ptr = new_ptr;
}
else
{
printf("%d %d %d not inserted. No memory available.\n",a,b,c);
}
}
This is the function that reads input from an output file. I am inserting a string into the list as a char*. The fscanf() has read the string in correctly.
void read_from_input2(rec_ptr & hptr, rec_ptr & tptr)
{
fp3=fopen("input2.txt","r");
if (fp3 == NULL)
printf("Error: Couldn't open file: input2.txt\n");
else
{
while(!feof(fp3))
{
int x,y,z;
char c1[10];
fscanf(fp3,"%d",&x);
fscanf(fp3,"%d",&y);
fscanf(fp3,"%d",&z);
fscanf(fp3,"%s",c1);
char *c2 = c1;
insert_rec(&hptr,&tptr,x,y,z,c2);
}
}
fclose(fp3);
}
This is the function where I am having problems. When I extract the data from the linked list, the variable c1 outputs garbage.
void write_to_output2(rec_ptr hptr)
{
fp4=fopen("output2.txt","w");
if (fp4 == NULL)
printf("Error: Couldn't open file: output2.txt\n");
else
{
if(hptr == NULL){
printf("List is empty.\n\n");
}
else{
while(hptr != NULL)
{
int x,y,z;
char *c1,*c2;
x = hptr->x;
y = hptr->y;
z = hptr->z;
c1 = hptr->c;
c2 = get_class(x,y,z);
fprintf(fp4,"%d %d %d %s %s\n",x,y,z,c1,c2);
hptr = hptr->next;
}
}
}
fclose(fp4);
}
If anyone can see my error please help me out. Thanks.
char c1[10];
/* ... */
char *c2 = c1;
insert_rec(&hptr,&tptr,x,y,z,c2);
The problem is c1 is on the stack of read_from_input2 and then you store a pointer to its contents. It will go out of scope when the while ends thus access to it will be invalid.
You'll want to strdup it (or equivalent).
char *c2 = strdup(c1);
/* or */
new_ptr->c = strdup(cs);
And don't forget to free it at some point.

Resources