Adding one Item to linked list creates two Items? - c

I'm trying to develop a device to copy files from one USB-drive to another, with both using the FAT-Filesystem. Therefor I use the "Vinculum II" microcontroller by FTDI. The Code is written in C.
To be able to copy all files, I need to know the names of the (sub-)directories on the drive because each of them has to be treated separately. There is a on-chip function to scan the current directory for files and sub-directories ('fat_dirTableFindFirst()' and 'fat_dirTableFindNext()').
I need to store the names of all directories (data type char *) which I received from the scan dynamically. I decided to use a linked-list. I use it like a stack (LIFO).
It's important for understanding the code, so I'll stress it again, that I have to scan each directory separately. So at first, I scan the root directory for its entries. Those ones that are further sub-directorys get pushed onto the stack.
After finishing the scan in the first directory, I grab the upper sub-directory off the stack (pop()). Then, I push the place marker "space" onto the stack, to be able to identify later, that I went into a deeper level/layer of that "directory-tree". If I don't find further directories during a scan, I move back to the last level and so on. Hence the scanning procedure should be similar to preorder traversing of a tree.
It works perfectly if there is max. one sub-directory in each directory. But if there are more than one, I get a confusing error: The first directory is pushed correctly, but all following entries appear twice on the stack! Because of that, the controller copies the same files again and again.
Single stepping through the program doesn't clearify why it happens. The code also writes the content of the stack before and after every push or pop into a .txt file with the same confusing results. It looks a bit like a push()-operation creates two Items, but only if it's called during that do...while loop.
Here's the interesting part of the code. vos_free() und vos_malloc() is equivalent to the usual free() an malloc() calls (ordner is the German word for directory or folder):
struct ordner {
char* data;
struct ordner* next;
};
void push(struct ordner** headRef, char* dirName)
{
struct ordner* newOrdner;
if (newOrdner = vos_malloc(sizeof(struct ordner)) != NULL)
{
newOrdner->data = dirName;
newOrdner->next = *headRef;
*headRef = newOrdner;
}
}
char* pop(struct ordner** headRef)
{
struct ordner* temp;
char* value = " ";
temp = *headRef;
value = *headRef->data; // "save" last element to return it
*headRef = temp->next;
vos_free(temp);
return (value);
}
while(1)
{
file_context_t fileToCopy; // File-Handle
struct ordner dummy;
struct ordner* head = &dummy;
dummy.next = NULL;
dummy.data = begin;
newScan: fat_dirTableFindFirst(fatContext1, &fileToCopy); if(firstRun == 0) // First filename in first scan is the name of the disk, and has to be ignored
{
fat_dirTableFindNext(fatContext1, &fileToCopy);
firstRun = 1;
}
do
{
// if the entry is a Directory, add it to the stack
if (fat_dirEntryIsDirectory(&fileToCopy) == 1)
{
strncpy(nextDir, (char*) &fileToCopy, 11);
push(&head, nextDir);
// The next if-statement usually cannot be true, because there can't be
// two files with the same name in one directory and the different levels/layers
// of sub-directories are separated by a place marker, but actually it becomes
// true (LEDs are flashing because of blink(3))
if (head->data == head->next->data) blink(3);
}
else
{
strncpy(nextFile, (char*) &fileToCopy, 11);
copyFile(fatContext1,fatContext2, nextFile); }
} while (fat_dirTableFindNext(fatContext1, &fileToCopy) == FAT_OK); // perform scan, until all items of the directory were scanned
// then the next (sub-)directory has to be opened to scan it
// there are two possibilities to proceed:
// (1) no directory found ("space" on stack) --> go back to last layer and open & scan the next directory there (if there is another one)
// (2) a new sub-directory was found --> open & scan it
change_layer: if (head != NULL)
{
nextDir = pop(&head); // get next Directory from stack
// Possibility (1)
if (nextDir == space)
{
// move back to last Directory
goto change_layer;
}
// Possibility (2): neue Unterordner gefunden
else
{
push(&head, space); // sign for entering next layer
//...
// open next directory
//...
goto newScan;
}
}
}
} // End while(1)
Can you tell me why it happens that one item appears twice on the stack? Is my Algorithm wrong?
After hours and hours of reasearching and coding I couldn't solve that problem.
Please forgive me my bad programming style with those assembler-like loops and my bad English (I'm from Germany :) )
Thanks in advance
Chris

Here is the declaration of a node for the linked list:
struct ordner {
char* data;
struct ordner* next;
};
So, the data has no storage associated with it. It is simply a pointer.
Then in your loop I do not see you call strdup() to allocate memory for a copy of the filename. You seem to be passing some buffer address directly to push() which saves a copy. This is a mistake.
I recommend that you change push() to call strdup() and save the filename. Then when you free an instance of ordner you must free data, the duplicate string, before you free the ordner instance.
Since in your design pop() also frees memory, you should change pop() so that the caller provides a buffer, and pop() copies the filename to the buffer before freeing the memory of the popped ordner instance.

You don't show where nextDir is declared, but at first glance, this seems likely:
You strncpy a directory name into nextDir. Then, you push this onto the stack. You now have for example an entry with data "dir1" on the stack.
If there is another directory within the same directory, you strncpy the next directory name into the same nextDir buffer, effectively overwriting it. You push it onto the stack. Its data pointer becomes the same nextDir buffer.
Now, both entries have the same data pointer, and the value is the value of the second entry, so the stack looks like "dir2","dir2".
If you want to have a string in each entry on the stack, you need to allocate the memory for each one (make sure you free it eventually though!)

I don't think you can declare variable like this within a while loop. The compiler might give you the same pointer over and over again.
while(1)
{
file_context_t fileToCopy; // File-Handle
struct ordner dummy;
struct ordner* head = &dummy;

Related

Recursive function : abort-condition

We need to create a binary tree which contains content of textfiles. The pointer selection_a and selection_b pointing to another textfile in the directory.
The structure of the textfiles is following:
line: Title
line: OptionA
line: OptionB
line: Text.
The first file is given as parameter while starting the program. All files should be saved at the beginning of the program. Then the text of the first file shows, and the user can input A or B to continue. Based on the selection, the text of File Option A/B is shown and the user can decide again.
The last file of a tree contains no Options: lines 2 and 3 are "-\n".
The problem is, this code only reads all the option A files of the first tree. It doesn't read in any B-Options. In the end, the program shows a memory access error.
I think the problem is that the readingRows function has no abort condition.
current->selection_a = readingRows(input_selection_a);
current->selection_b = readingRows(input_selection_b);
I know the code may be kind of chaotic, but we are beginners in programming. Hope anybody can help us to write an abort-condition.
The function should be aborted if the content of option A (line 3) is "-\n".
Here is the whole function:
struct story_file* readingRows(FILE *current_file)
{
char *buffer = fileSize(current_file);
char *delimiter = "\n";
char *lines = strtok(buffer, delimiter);
int line_counter = 0;
struct story_file *current = malloc(sizeof(struct story_file));
while(lines != NULL)
{
if(line_counter == 0)
{
current->title = lines;
}
else if(line_counter == 1)
{
char *filename_chapter_a = lines;
FILE *input_selection_a = fopen(filename_chapter_a, "r");
if(input_selection_a)
{
current->selection_a = readingRows(input_selection_a);
}
fclose(input_selection_a);
}
else if(line_counter == 2)
{
char *filename_chapter_b = lines;
FILE *input_selection_b = fopen(filename_chapter_b, "r");
if(input_selection_b)
{
current->selection_b = readingRows(input_selection_b);
}
fclose(input_selection_b);
}
else if (line_counter >= 3)
{
current->text = lines;
}
lines = strtok(NULL, delimiter);
line_counter++;
}
return current;
}
There are two items that define a terminating recursive function:
One or more base cases
Recursive calls that move toward a base case
Your code has one base case: while (lines!=NULL) {} return current;, it breaks the while loop when lines is NULL and returns current. In other words, within any particular call to your function, it only terminates when it reaches the end of a file.
Your code moves toward that base case as long as your files do not refer to each other in a loop. We know this because you always read a line, take an action according to your if-else block, and the read the next line. So you always move toward the end of each file you read.
But as you note, the issue is that you don't have a case to handle "no Options", being when lines 2 or 3 are "-\n". So right now, even though you move through files, you are always opening files in line 2. Unless a file is malformed and does not contain a line 2, your recursive call tree never ends. So you just need to add another base case that looks at whether the beginning of lines matches "-\n", and if it does, return before the recursive call. This will end that branch of your recursive tree.
Inside of your while loop, you will need code along the lines of:
if `line_counter` is `2` or `3`
if `lines` starts with your terminating sequence "-\n"
return current
else
`fopen` and make the recursive call
In the parent function that made the recursive call, it will move to the next line and continue as expected.
P.S. Make sure you use free for each malloc you do.

C Programming - fprintf and printf in while cicle doesn't work

I'm getting a strange problem with a while cicle inside of a function.
I have to look for the extreme vertices of a .ply model. All the data is stored in a linked list. When I'm done creating the list, I call the findExtremeVertex function, that modifies 6 global variables (leftVertex, rightVertex, downwardVertex, upwardVertex, backVertex and frontVertex).
To see if the values are right (the models I use are a bit too big to control every single line to find the maximum of every vertex) I decided to print every change in the max-min values but, when I try to print them in a file, the file is empty. Why is that? Also, when I saw that the file was empty, I tried to print something directly in the console but that didn't work either.
Here's the code of the funcion:
void findExtremeVertex(Vertex *vertex){
FILE *modelInfoFile;
int i = 0;
///Giving data to direction-vertices pointers
leftVertex = malloc(sizeof(Vertex));
rightVertex = malloc(sizeof(Vertex));
upwardVertex = malloc(sizeof(Vertex));
downwardVertex = malloc(sizeof(Vertex));
frontVertex = malloc(sizeof(Vertex));
backVertex = malloc(sizeof(Vertex));
///Giving the direction-vertices the values of the parameter
leftVertex = vertex;
rightVertex = vertex;
upwardVertex = vertex;
downwardVertex = vertex;
frontVertex = vertex;
backVertex = vertex;
///Opening file
modelInfoFile = fopen(us2, "w");
if(modelInfoFile == NULL){
printf("Error in file opening. Exiting.");
exit(EXIT_FAILURE);
}
///Scrolling the list
while(vertex->prev != NULL){
vertex = vertex->prev;
///If the given element of the list is more to the right than the global variable,
///I assign the values of the element to the global variable
if(vertex->vertexCoordinates.x > rightVertex->vertexCoordinates.x){
rightVertex = vertex;
}
/**
I'm omitting the other if constructs because are basically
the same, but the syntax is correct
**/
///Printing in file the cycle information
fprintf(modelInfoFile, "********** CYCLE %d **********\n\n", i);
fprintf(modelInfoFile, "Vertex sx\n");
fprintf(modelInfoFile, "%1.4f %1.4f %1.4f %1.4f %1.4f %1.4f\n\n", leftVertex->vertexCoordinates.x,
leftVertex->vertexCoordinates.y,
leftVertex->vertexCoordinates.z,
leftVertex->vertexNormals.x,
leftVertex->vertexNormals.y,
leftVertex->vertexNormals.z);
/**
Again, I'm omitting some repetitions but the syntax is correct
**/
}
}
I call this function in another function, but there's no segmentation fault signal, the compiler doesn't tell me anything, the program doesn't crash. I have no clue of the error, except from the fact that the file where I print the infos about the cycles is empty. What am I doing wrong?
There are many problems in your code.
You malloc() 6 variables and never use any of them, and you don't check if malloc() succeeded.
You never call fclose() or fflush() so maybe you are seeing the file before the data is flushed to the disk.
You reassign all the *Vertex (except for rightVertex) variables after they are malloc()ed to the same pointer vertex which means
You are causing a memory leak.
You are using 6 variables for a single pointer.
All the *Vertex variables are not declared inside the function which means that they are in the global scope, that is very likely a bad design choice. Given the code you posted it's not possible to tell whether or not global variables are the right choice, but 99% of the time they are a bad choice and there is a much more elegant and safe way to do things.
The bold point above is likely the reason why your program is behaving as it is.
The code
leftVertex = vertex;
rightVertex = vertex;
upwardVertex = vertex;
downwardVertex = vertex;
frontVertex = vertex;
backVertex = vertex;
sets the pointer value but not the actual value. You malloc space, get a pointer to that space, and then throw that pointer away setting it to the pointer of virtex.
Do you mean to use
*leftVertex = *vertex;
*rightVertex = *vertex;
*upwardVertex = *vertex;
*downwardVertex = *vertex;
*frontVertex = *vertex;
*backVertex = *vertex;
///Scrolling the list
while(vertex->prev != NULL){
vertex = vertex->prev;
And what happens if vertex is NULL after this?
You're checking if it's NULL, then changing it's value such that it can become NULL.
///Opening file
if(modelInfoFile == NULL){
printf("Error in file opening. Exiting.");
exit(EXIT_FAILURE);
}
I don't see you opening file.
if((modelInfoFile=fopen(filename,"w")) == NULL){
Should work.
EDIT
In you while loop you change -
vertex = vertex->prev;
But in fprintf you store in file in value of leftVertex->vertexCoordinates.x
So how do you expect to print inside file correctly.

C recursively build tree using structure pointer

I'm now implementing Barnes-Hut Algorithms for simulating N-body problem. I only want to ask about the building-tree part.
There are two functions I made to build the tree for it.
I recursively build the tree, and print the data of each node while building and everything seems correct, but when the program is back to the main function only the root of the tree and the child of the root stores the value. Other nodes' values are not stored, which is weird since I printed them during the recursion and they should have been stored.
Here's some part of the code with modification, which I thought where the problem might be in:
#include<...>
typedef struct node{
int data;
struct node *child1,*child2;
}Node;
Node root; // a global variable
int main(){
.
set_root_and_build(); // is called not only once cuz it's actually in a loop
traverse(&root);
.
}
Here's the function set_root_and_build():
I've set the child pointers to NULL, but didn't show it at first.
void set_root_and_build(){
root.data = ...;
..// set child1 and child2 =NULL;
build(&root,...); // ... part are values of data for it's child
}
And build:
void build(Node *n,...){
Node *new1, *new2 ;
new1 = (Node*)malloc(sizeof(Node));
new2 = (Node*)malloc(sizeof(Node));
... // (set data of new1 and new2 **,also their children are set NULL**)
if(some condition holds for child1){ // else no link, so n->child1 should be NULL
build(new1,...);
n->child1 = new1;
//for debugging, print data of n->child1 & and->child2
}
if(some condition holds for child2){ // else no link, so n->child2 should be NULL
build(new2,...);
n->child1 = new2;
//for debugging, print data of n->child1 & and->child2
}
}
Nodes in the tree may have 1~2 children, not all have 2 children here.
The program prints out the correct data when it's in build() function recursion, but when it is back to main function and calls traverse(), it fails due to a segmentation fault.
I tried to print everything in traverse() and found that only the root, and root.child1, root.child2 stores the value just as what I've mentioned.
Since I have to called build() several times, and even in parallel, new1 and new2 can't be defined as global variables. (but I don't think they cause the problem here).
Does anyone know where it goes wrong?
The traverse part with debugging info:
void traverse(Node n){
...//print out data of n
if(n.child1!=NULL)
traverse(*(n.child1))
...//same for child2
}
You may not be properly setting the children of n when the condition does not hold. You might want this instead:
void set_root_and_build()
{
root.data = ...;
build(&root,...); // ... part are values of data for it's child
}
void build(Node *n,...)
{
n->child1 = n->child2 = NULL;
Node *new1, *new2;
new1 = (Node*) malloc(sizeof(Node));
new2 = (Node*) malloc(sizeof(Node));
// set data of new1 and new2 somehow (read from stdin?)
if (some condition holds for new1)
{
n->child1 = new1;
build(n->child1,...);
//for debugging, print data of n->child1
}
else
free(new1); // or whatever else you need to do to reclaim new1
if (some condition holds for new2)
{
n->child2 = new2;
build(n->child2,...);
//for debugging, print data of n->child2
}
else
free(new2); // or whatever else you need to do to reclaim new2
}
Of course, you should be checking the return values of malloc() and handling errors too.
Also, your traversal is a bit strange as it recurses by copy rather than reference. Do you have a good reason for doing that? If not, then maybe you want:
void traverse(Node *n)
{
...//print out data of n
if (n->child1 != NULL)
traverse(n->child1)
...//same for child2
}
The problem in your tree traversal is that you certainly process the tree until you find a node pointer which is NULL.
Unfortunately when you create the nodes, these are not initialized neither with malloc() nor with new (it would be initialized with calloc() but this practice in cpp code is as bad as malloc()). So your traversal continues to loop/recurse in the neverland of random pointers.
I propose you to take benefit of cpp and change slightly your structure to:
struct Node { // that's C++: no need for typedef
int data;
struct node *child1,*child2;
Node() : data(0), child1(nullptr), child2(nullptr) {} // Makes sure that every created are first initalized
};
And later get rid of your old mallocs. And structure the code to avoid unnecessary allocations:
if(some condition holds for child1){ // else no link, so n->child1 should be NULL
new1=new Node; // if you init it here, no need to free in an else !!
build(new1,...);
n->child1 = new1;
...
}
if (... child2) { ... }
Be aware however that poitners allocated with new should be released with delete and note with free().
Edit: There is a mismatch in your code snippet:
traverse(&root); // you send here a Node*
void traverse(Node n){ // but your function defines an argument by value !
...
}
Check that you didn't overllok some warnings from the compiler, and that you have no abusive cast in your code.

Assignment of a pointer within a struct NOT WORKING, why is the value not changing?

For a school project I am supposed to implement a simplified version of the UNIX filesystem using only linked list structures. I am currently having a problem with my mkfs() function, which is supposed to simply initialize a filesystem.
My header file that creates the structures I am using is here:
typedef struct Lines {
char line[82];
struct Lines *next;
} Lines;
typedef struct Node {
char *name;
int id;
struct Node *parent;
struct Node *next;
union {
char line[82];
struct Node *children;
} contents;
} Node;
typedef struct Filesystem {
char *name;
struct Node *root;
struct Node *current;
} Filesystem;
Here is the method in my separate file which #includes this header file:
void mkfs(Filesystem *files) {
Node *root = NULL; /* Creates a pointer to the directory we will use as
* the root directory for this filesystem*/
files = (Filesystem *)malloc(sizeof(*files)); /* Allocates space for the the
* filesystem structure */
if(files == NULL){ /* If there is no memory available, prints error message
* and does nothing else */
printf("Memory allocation failed!\n");
} else {
root = (Node *)malloc(sizeof(*root)); /* Allocates space for the root
* directory of the filesystem. */
if(root == NULL) { /* If there is no memory available, prints error
* message and frees memory obtained thus far, but then
* does nothing else */
printf("Memory allocation failed!\n");
free(files);
} else {
/* Allocates space for the root directory's name string */
root->name= (char *)malloc(sizeof(char)*(strlen("/")+1));
if(root->name == NULL) { /* If there is no memory available, prints error
* message and frees memory obtained thus far,
* but then does nothing else */
printf("Memory allocation failed!\n");
free(files);
free(root);
} else {
root->name = "/"; /* Defines the root directory as being named by the
* forward slash */ /* DO STR CPY HERE ITS CHANGING THE ADDRESS */
root->contents.children = NULL;
root->next = NULL;
root->parent = NULL; /* UHH CHECK ON THIS NOOO CLUE IF ITS RIGHT FUUU*/
files->root = root; /* The filesystems pointer to a directory is set
* to point to the root directory we just allocated
* space for and set up */
files->current = root; /* Sets the filesystems current directory to
* point to the root directory as well, because
* it is the only directory in existence for this
* filesystem at this point. */
}
}
}
}
The problem I am having is that when I run gdb and step through each line, the last two assignment lines ARE NOT CHANGING the contents of file->root and file->current.
For example, here I print the contents of files->root, run the line files->root = root, and then print again, and you can see the address has not changed. However if I just print root, the thing I am trying to assign it to, it clearly has a different value that files->root SHOULD have been set to:
(gdb) print files->root
$12 = (struct Node *) 0x400660
(gdb) step
(gdb) print files->root
$13 = (struct Node *) 0x400660
(gdb) print root
$14 = (Node *) 0x602030
Does anyone have any idea as to why an assignment might not work in this case? This is currently ruining my whole project, so any insight would be greatly appreciated. Thank you!!!
It looks like your mkfs function is accepting a pointer to an already-existing Filesystem and then you are trying to allocate memory for a new Filesystem at a new memory location. There are two common conventions for a function like this: either it accepts no parameters and returns a pointer to a struct, or it accepts a pointer to an already-allocated struct and populates that struct. The reason it appears like the data isn't changing is that you're actually creating and populating a second struct, and leaving the caller's struct unchanged.
Here's an example of the first case, simplifying the function to just the memory allocation part:
Filesystem * mkfs() {
Filesystem *files = (Filesystem *)malloc(sizeof(Filesystem));
// (error handing omitted for brevity)
// populate the files struct as appropriate...
Node *root = (Node *)malloc(sizeof(Node));
files->root = root;
// etc, etc as you currently have
return files;
}
// In this case you should also provide a way for the caller to free a filesystem,
// which will free everything you allocated during mkfs:
void freefs(Filessystem *files) {
// first free any buffers you allocated inside the struct. For example:
free(files->root);
// then free the main filesystem struct
free(files);
}
The caller then deals with this object using these two functions. For example:
int main() {
Filesystem *files = mkfs();
// now "files" is ready to use
freefs(files); // free the objects when we're done with them.
}
Here's an example of the second case, which assumes that the caller already allocated an appropriate buffer, and it just needs to be populated:
void mkfs(Filesystem *files) {
// populate the files struct as appropriate...
Node *root = (Node *)malloc(sizeof(Node));
files->root = root;
// etc, etc as you currently have
}
void freefs(Filesystem *files) {
// still need to clean up all of the ancillary objects
free(files->root);
// etc, etc
}
In this case the calling function has some more work to do. For example:
int main() {
Filesystem *files = (Filesystem *)malloc(sizeof(Filesystem));
mkfs(files);
// now "files" is ready to use
freefs(files); // free the objects when we're done with them.
}
Both patterns are valid; the former is useful if you expect that the caller will need to be able to control how memory is allocated. For example, the caller might decide to allocate the filesystem on the stack rather than the heap:
int main() {
Filesystem files;
mkfs(&files);
// now "files" is ready to use
freefs(&files); // free the ancillary objects when we're done with them.
// "files" is still allocated here, but it's no longer valid
}
The latter takes care of the allocation on behalf of the caller. Since your function allocates further structures on the heap it's necessary to include a cleanup function in both cases.

Value of head of linked list silently changes when list grows past 100 elements

I need to make some operations on a list of files with particular extension (*.bob), all stored in the same directory. The files are image frames, and their name format is frame_XXXX.bob. I don't know the number of frames a priori, and I need to make sure I process them in order (from frame 0 to last one). I read the content of the folder with struct dirent *readdir(DIR *dirp), but since it doesn't guarantee files will be read in alphabetical order (even though it always seems to), I want to put them into a single linked list, and then sort them before processing further.
I save the head of the list before populating it to a pointer filesListStart, then read the entire folder content, adding each entry to the list if it has ".bob" extension. This all works great when I have up to 100 frames, but for some reason breaks down above that - the value of what pointer filesListStart points at doesn't contain the filename of the first entry in the list anymore. The code doesn't use any numerals, so I don't know what would be the significance of going over 100 elements.
I wrote out memory address of filesListStart before I start populating the list, and after, and they are the same, but values they show at magically change. When I set filesListStart it points at object with field fileName equals to "frame_0000.bob" (which is as expected), but after populating the list the name it points at becomes "e_0102.bob".
The list structure is defined as
// List structure
struct FilesList {
char *fileName ;
struct FilesList *next ;
} ;
The code in question is:
DIR *moviesDir ;
moviesDir = opendir("movies") ;
if(moviesDir == NULL)
{
printf("Make Movie failed to open directory containing bob frames\n") ;
return ;
}
struct dirent *dirContent ;
// Get first .bob frame name from the directory
dirContent = readdir(moviesDir) ;
// isBobFile(dirContent) returns 1 if entry has ".bob" extension and 0 otherwise
while( !isBobFile(dirContent) )
{
dirContent = readdir(moviesDir) ;
}
struct FilesList *filesList = (struct FilesList*)
malloc( sizeof(struct FilesList) ) ;
// Initialize the list start at that first found .bob frame
filesList->fileName = dirContent->d_name;
// And save the head of the list
struct FilesList *filesListStart = filesList ;
printf("FilesListStart: %s\n", filesListStart->fileName) ;
printf("Address is: %p\n", filesListStart) ;
// For all other bob frames
while( (dirContent = readdir(moviesDir) ) != NULL )
{
if( isBobFile(dirContent) )
{
struct FilesList *temporaryNode = (struct FilesList*)
malloc( sizeof(struct FilesList) );
temporaryNode->fileName = dirContent->d_name ;
filesList->next = temporaryNode ;
filesList = temporaryNode ;
}
}
// Set the 'next' pointer of the last element in list to NULL
filesList->next = NULL ;
// close stream to directory with .bob frames
closedir(moviesDir) ;
// Check what FilesListStart points at
printf("FilesListStart: %s\n", filesListStart->fileName) ;
printf("Address is: %p\n", filesListStart) ;
// Rest of the code
You should be making a copy of dirContent->d_name rather than using the actual value.
The runtime libraries are free to change the contents of that dirent structure whenever you call readdir and, if all you've stored is it's address, the underlying memory may change. From the POSIX man-pages:
The pointer returned by readdir() points to data which may be overwritten by another call to readdir() on the same directory stream.
In other words, replace the lines:
filesList->fileName = dirContent->d_name;
temporaryNode->fileName = dirContent->d_name ;
with:
filesList->fileName = strdup (dirContent->d_name);
temporaryNode->fileName = strdup (dirContent->d_name);
assuming you have a strdup-like function and, if not, you can get one cheap here.
If it's only changing after 100 calls, it's probably the runtime trying to be a bit more intelligent but even it can't store an infinite number so it probably sets a reasonable limit.
Just remember to free all those char pointers before you free the linked list nodes (somewhere in that "rest of code" section presumably).

Resources