For an assignment I'm supposed to implement a crude file system in linux, and to get a better idea of how it's going to work, I'm messing around in C rather than going directly into the syscalls. I'm planning to make a linked list, where each node has the file's name, a pointer to the data (a string, basically), and a pointer to the next node (obviously). So my struct is basically
char *data;
char file[30];
struct node *next;
I decided to make the struct contain a char pointer because I don't want to just make it a huge character array as that would waste space if it was just a single word. However, I'm having a hell of a time getting the char pointer to actually work. Every time I go to print out the linked list I get a segmentation violation. Here's how I make the "files", as it is, it just takes a string (filename here) and sets both the filename and data to that string, for simplicity:
struct node *new_node;
new_node = malloc(sizeof( struct node));
char *ptr = malloc(strlen(filename));
strcpy(ptr, filename);
(*new_node).data = ptr;
strcpy((*new_node).name, filename);
printf("data = %s\n", (*new_node).data);
(*last).next = new_node;
last = new_node;
The data is set after assigning it here, but when traversing the nodes I get a segmentation violation. At first I thought it was a memory lifetime issue, but if it were, getting the filename itself would cause a seg violation, and it didn't do that until I added the code to print out the data. For further reference, here is my code to print the nodes
printf("Node #%d has name: %s and data contents: %s\n", i, (*curr_node).name,
(*curr_node).data);
It's possible I'm just using pointers totally wrong, I haven't really used them in a long time. So... anyone have any idea what I'm doing wrong here?
Posts
Also, it looks like your second code listing is part of a function. It would be helpful if you posted the entire function so we can see what the parameters are to the function, etc.
An unrelated aside: would usually be written . There's no difference, but the second form is easier to read.
Out of curiosity though, do you have any suggestions regarding how to cut down on that?
If you need to see just how much memory you're leaking, there's a tool called valgrind that's standard on most Linux systems. Just do "valgrind --tool=memcheck --show_unreachable=yes your_program" (I believe that's right, at any rate) to see how bad it is. Additionally, you also declare variables all willy-nilly, which is generally discouraged in C. To catch that, we always had our students (I used to be a C TA) compile their programs with the following GCC command: "gcc -Wall -Werror -ansi -pedantic". This will turn on all warnings, make all warnings errors, compile in C89 mode, and be really pedantic about C89 syntax (respectively).
I don't see any printk's in your code above, so obviously it's changed a little bit. Try posting it again (in a spoiler if you want to save space) so we can see where you're at now.