• 0

C - Step linked list analysis


Question

http://pastebin.com/BBHxd0iY

I have to use the the following file shuffle.csv to identify which parish from the most populated county has the least people. It is done line by line, for instance:

county A, parish B, Population B

county A, parish C, Population C

county A -> parish B or C -> Population B or C

If ( pop C < pop B ) county A -> parish C -> Population C

county A -> population + = Pop C

The most populated county is placed in the root of the linked list and then fprintf("output.csv"... ), in each interaction ( line by line ) evaluation til that line.

All the counties are added.

The least populated parish from the corresponding county is updated.

It very easy but I cannot spot the bug. It compiles well but when I run it the output, which is placed in a file named output.csv, is wrong. I have spent at least 5 hours revising the code, debugging, testing, breakpoints and I cant find the little *****r xD. I would appreciate it if you could help me out.

Input file structure:

District , county , parish, population

Grande Porto, Vila do Conde, Rio Mau, 1907

Output file structure:

fprintf( stdout, "%s, %s, %d\n", base->root->minusParish->parishName, base->root->countyName, base->root->minusParish->population);

Arcos, Vila do Conde, 869

...

Ferreiro, Vila do Conde, 660

...

Outeiro Maior, Vila do Conde, 378

...

It just prints Vila do Conde parish and it shouldn't.

HEADER


typedef struct {
int population;
char *parishName;
} parish;

typedef struct nextCounty {
char *countyName;
int population;
parish *minusParish;
struct nextCounty *next;
} county;

typedef struct {
int numberCounties;
county *root;
} core;

int list_assign( core *l, int pos, char **str, int people);

int list_insert( core *l, int pos, county *curr);

county* lista_removeTOSORT(core *l, int pos);

county * list_search( core *l, char* str, int *pos);

int list_sort( core *l, int posiVerifi, county *foundAddr);
[/CODE]

[b][u][color=#b22222]MAIN[/color][/u][/b]

[CODE]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lista.h"

county* createCounty( char *name, int people ) {

county *ptr;

if ( ( ptr = ( county *) malloc( sizeof(county) * 1 ) ) == NULL ) return NULL;

ptr->countyName = name;
ptr->population = people;
ptr->next = NULL;

return ptr;
}

parish* createParish ( char *name, int people ) {

parish *ptr;

if ( ( ptr = ( parish *) malloc( sizeof(parish) * 1 ) ) == NULL ) return NULL;

ptr->parishName = name;
ptr->population = people;

return ptr;
}

FILE* readlnVeriPlace( FILE *input, core *listCore) {

int i;
int people;
county *countyList, *foundAddress;
parish *parishList;
char *countyMalloc;
char *parishMalloc;
char ch;
int position;


if ( input == NULL || listCore == NULL ) return NULL;

parishMalloc = (char *) malloc ( sizeof(char) * 50 );
countyMalloc = (char *) malloc ( sizeof(char) * 50 );

if ( parishMalloc == NULL || countyMalloc == NULL ) return input;

// READLINE

while ( ( ch = fgetc(input) ) != ',' );

i = 0;
while ( ( ch = fgetc(input) ) != ',' ) {
countyMalloc[i] = ch;
i++;
}
countyMalloc[i] = '\0';

i = 0;
while ( ( ch = fgetc(input) ) != ',' ) {
parishMalloc[i] = ch;
i++;
}
parishMalloc[i] = '\0';

fscanf(input, "%d", &people);

while ( fgetc(input) != '\n' && !feof(input)) ;

//ENDREADLINE

foundAddress = list_search( listCore, countyMalloc, &position);

if ( foundAddress != NULL ) {
list_assign( listCore, position, &parishMalloc, people);
free(countyMalloc);
}
else {
parishList = createParish ( parishMalloc, people );
countyList = createCounty ( countyMalloc, people );
countyList->minusParish = parishList;
foundAddress = countyList;
if ( listCore->numberCounties == 0 ) list_insert( listCore, -1, countyList);
}

list_sort( listCore, position, foundAddress);

return input;
}


int main( int argc, const char *argv[] ) {

FILE *input;
FILE *output;
core *base;

if ( argc != 2 ) {
fprintf( stdout, "%s shuffle.csv\n", argv[0] );
exit(1);
}

if ( ( input = fopen( argv[1], "r") ) == NULL ) {
fprintf( stdout, "Not possible to open the file.\n");
exit(2);
}

if ( ( output = fopen ( "output.csv", "w") ) == NULL ) exit(3);

if ( ( base = (core *) malloc( sizeof(core) * 1) ) == NULL ) exit (4);

base->numberCounties = 0;
base->root = NULL;

while ( !feof(input) ) {
input = readlnVeriPlace( input, base );
fprintf( stdout, "%s, %s, %d\n", base->root->minusParish->parishName, base->root->countyName, base->root->minusParish->population);
}

return 0;
}
[/CODE]

[color=#b22222][b][u]Function Library[/u][/b][/color]

[CODE]
#include "lista.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int list_assign( core *l, int pos, char **str, int people)
{
int i = 0;
county *aux;

if (l == NULL || pos < 0)
return -1;

aux = l->root;

for (i = 0; i < pos && aux != NULL; i++)
aux = aux->next;

if (aux == NULL)
return -1;

aux->population += people;

if ( people < aux->minusParish->population ) {
aux->minusParish->population = people;
free(aux->minusParish->parishName);
aux->minusParish->parishName = *str;
} else free(*str);

return pos;
}


int list_insert( core *l, int pos, county *curr)
{
int i = 0;
county *temp;

if (l == NULL || pos < -1 || pos >= l->numberCounties) return -1;

temp = l->root;

if (curr == NULL) return -1;

l->numberCounties++;

if(pos == -1)
{
if (temp == NULL) l->root = curr;
else
{
while (temp->next != NULL) temp = temp->next;
temp->next = curr;
}

return l->numberCounties-1;
}

if (pos == 0)
{
curr->next = temp;
l->root = curr;
return pos;
}

for (i = 0; i < pos-1 && temp != NULL; i++) temp = temp->next;

curr->next = temp->next;
temp->next = curr;

return pos;
}


county* lista_removeToSort(core *l, int pos)
{
int i = 0;
county *prev, *curr;

if (l == NULL || pos < 0 || pos >= l->numberCounties) return NULL;

curr = l->root;

l->numberCounties--;

if(pos == 0)
{
l->root = curr->next;
curr->next = NULL;
return curr;
}

for( i = 0; i < pos && curr->next; i++)
{
prev = curr;
curr = curr->next;
}

prev->next = curr->next;

curr->next = NULL;
return curr;
}

county * list_search( core *l, char* str, int *pos)
{

int i = 0;
county *aux;

if( l == NULL ) return NULL;

for (aux = l->root; aux != NULL; aux = aux->next, i++)
{
if ( strcmp( aux->countyName, str) == 0) {
*pos = i;
return aux;
}
}

*pos = -1;
return NULL;
}

int list_sort( core *l, int posiVerifi, county *foundAddr)
{
county *ptr;
int i = 0;

if ( l == NULL ) return -1;
if ( l->root == NULL || l->numberCounties == 1) return 0;

if ( posiVerifi != -1 ) foundAddr = lista_removeToSort( l, posiVerifi);

for ( ptr = l->root; ptr != NULL; ptr = ptr->next, i++ ) {
if ( ptr->population < foundAddr->population ) {
list_insert( l, i, foundAddr);
}
}
list_insert( l, -1, foundAddr);

return 0;
}[/CODE]

Link to comment
https://www.neowin.net/forum/topic/1078483-c-step-linked-list-analysis/
Share on other sites

6 answers to this question

Recommended Posts

  • 0

        for ( ptr = l->root; ptr != NULL; ptr = ptr->next, i++ ) {
if ( ptr->population < foundAddr->population ) {
list_insert( l, i, foundAddr);
return 0;
}
}
[/CODE]

Well spotted :woot:, however it doesn't produce the correct output so there must be another bug somewhere :|.

Thanks a lot.

  • 0

I think there's a problem with your list insertions in function readlnVeriPlace:

if ( listCore-&gt;numberCounties == 0 ) list_insert( listCore, -1, countyList);

Unless I'm mistaken, your code will only insert the first county because afterwards listCore->numberCounties will be non-zero, therefore list_insert doesn't get executed again.

And personally, I would read a whole line at a time, then use strtok to parse it using ',' as a delimiter.

list_search is going to get expensive as well towards the end of the file.

  • 0

Nice, thanks for your help :rofl: . The sort function does insert. What it does is see if the county is in the list or not with the help of list_search, if it was there (in the list) it removesToSort ( connects the neighbours but does not free )and searches for the correct place and then inserts it there.

The problem was that after the first run, a new item could not be inserted because list_sort had a control statement that was absurd :blush: ,

 if ( l->root == NULL || l->numberCounties == 1) return 0;[/CODE]

So, nothing would ever be added because l->numberCounties would never increment.

:pinch: I removed that instruction

[CODE]if ( listCore->numberCounties == 0 ) list_insert( listCore, -1, countyList);[/CODE]

And replaced,

[CODE] if ( l->root == NULL || l->numberCounties == 1) return 0;[/CODE]

with:

[CODE]if ( l->numberCounties == 0 ) { list_insert( l, -1, foundAddr); return 0; }[/CODE]

  • 0

Nice, thanks for your help :rofl: . The sort function does insert. What it does is see if the county is in the list or not with the help of list_search, if it was there (in the list) it removesToSort ( connects the neighbours but does not free )and searches for the correct place and then inserts it there.

The problem was that after the first run, a new item could not be inserted because list_sort had a control statement that was absurd :blush: ,

 if ( l->root == NULL || l->numberCounties == 1) return 0;[/CODE]

So, nothing would ever be added because l->numberCounties would never increment.

:pinch: I removed that instruction

[CODE]if ( listCore->numberCounties == 0 ) list_insert( listCore, -1, countyList);[/CODE]

And replaced,

[CODE] if ( l->root == NULL || l->numberCounties == 1) return 0;[/CODE]

with:

[CODE]if ( l->numberCounties == 0 ) { list_insert( l, -1, foundAddr); return 0; }[/CODE]

I see. I knew there was a problem with the insertion somewhere, because numberCounties was always 1 after the first insert in readlnVeriPlace.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Dopamine 3.0.6 by Razvan Serea Dopamine is an awesome free audio player which tries to make organizing and listening to music as simple and pretty as possible. Dopamine has been designed for Windows 7, Windows 8.x and Windows 10 and plays mp3, ogg vorbis, flac, wma and m4a/aac music formats quite well. The best part? It's created by long-time Neowin member, Raphaël Godart. If you’re looking for a music player to handle a large music collection, you should definitely give Dopamine a try. Dopamine 3.0.6 changelog: Fixed Manually edited album covers are overwritten on the next collection refresh Fixed AppImage package not working on modern GNU/Linux distributions Deleting song from playlist sometimes fails Playback controls only work when clicking on upper half of the buttons It's unclear that files must be tagged with an external ReplayGain scanner (for example rsgain) before normalization can take effect. Change to Artist or Album tags is not reflected in the song list view nor in the Now Playing information ReplayGain issues Smart playlist filters ignore text containing accents or other special characters Some MP3 files trigger an "MPEG header not found" error due to a too-narrow initial MPEG header scan range Changed Updated the Vietnamese translation Download: Dopamine 3.0.6 | 122.0 MB (Open Source) Links: Home Page | Forum Discussion | Screenshot | Other OSes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • BleachBit 6.0.1 Beta by Razvan Serea When your computer is getting full, BleachBit quickly frees disk space. When your information is only your business, BleachBit guards your privacy. With BleachBit you can free cache, delete cookies, clear Internet history, shred temporary files, delete logs, and discard junk you didn't know was there. Designed for Linux and Windows systems, it wipes clean thousands of applications including Firefox, Microsoft Edge, Google Chrome, Opera, Safari, and more. Beyond simply deleting files, BleachBit includes advanced features such as shredding files to prevent recovery, wiping free disk space to hide traces of files deleted by other applications, and vacuuming Firefox to make it faster. Better than free, BleachBit is open source. BleachBit has many useful features: Delete your private files so completely that "even God can't read them" according to South Carolina Representative Trey Gowdy. Simple operation: read the descriptions, check the boxes you want, click preview, and click delete. Multi-platform: Linux and Windows Free of charge and no money trail Free to share, learn, and modify (open source) No adware, spyware, malware, browser toolbars, or "value-added software" Translated to 64 languages besides American English Shred files to hide their contents and prevent data recovery Shred any file (such as a spreadsheet on your desktop) Overwrite free disk space to hide previously deleted files Portable app for Windows: run without installation Command line interface for scripting and automation CleanerML allows anyone to write a new cleaner using XML Automatically import and update winapp2.ini cleaner files (a separate download) giving Windows users access to 2500+ additional cleaners Frequent software updates with new features Going beyond standard deletion of files, BleachBit has several advanced cleaners: Clear the memory and swap on Linux Delete broken shortcuts on Linux Delete the Firefox URL history without deleting the whole file—with optional shredding Delete Linux localizations: delete languages you don't use. More powerful than localepurge and available on more Linux distributions. Clean APT for Debian, Ubuntu, Kubuntu, Xubuntu, and Linux Mint Find widely-scattered junk such as Thumbs.db and .DS_Store files. Execute yum clean for CentOS, Fedora, and Red Hat to remove cached package data Delete Windows registry keys—often where MRU (most recently used) lists are stored Delete the OpenOffice.org recent documents list without deleting the whole Common.xcu file Overwrite free disk space to hide previously files Vacuum Firefox, Google Chrome, Liferea, Thunderbird, and Yum databases: shrink files without removing data to save space and improve speed Surgically remove private information from .ini and JSON configuration files and SQLite3 databases without deleting the whole file Overwrite data in SQLite3 before deleting it to prevent recovery (optional) BleachBit 6.0.1 Beta release notes: BleachBit 6.0.1 beta is now available for testing. This maintenance-focused release includes bug fixes, updated translations, and a range of safe enhancements. This release fixes a Windows security issue that could allow arbitrary file deletion during privileged cleaning (reported by Zeze with TeamT5). It also adds new cleaners (including a DNS cache cleaner, Claude Code, and Visual Studio Code forks), support for multiple Chrome and Edge profiles, new deep scan options for developer directories like node_modules and venv, and safer, faster file shredding. All Platforms Added cleaners for Claude Code, DNS cache, and many Visual Studio Code forks. Added support for multiple Chrome and Edge profiles. Chrome can now clean downloaded AI models. Deep Scan can optionally remove venv, __pycache__, node_modules, and .angular directories. Deep Scan is faster by skipping directories on the keep list. File shredding is safer, faster, and leaves fewer recoverable traces. Improved handling of cookies, symlinks, Unicode filenames, external processes, and configuration files. Improved Expert Mode warnings and long warning dialogs. Fixed crashes related to cleaner detection, invalid Unicode, and malformed cleaner data. Clipboard is now cleared automatically after shredding files via paste operations. Linux Added AppImage support. Added cleaners for Visual Studio Code, Codeium, Librewolf (.deb), Transmission (Flatpak), and Profanity. Improved Linux trash detection, including Snap-installed applications and mounted drives. Fixed Wayland root CLI issues and several Snap-related problems. Improved package dependencies, AppStream metadata, and desktop file handling. Fixed startup crashes when Python Requests is unavailable. Windows Fixed a security vulnerability that could allow arbitrary file deletion when cleaning with elevated privileges. Added %WindowsSystem% variable support. Improved clipboard clearing using native Windows APIs. Improved installer experience on unsupported Windows versions. Reduced installer size and improved application robustness. Fixed Unicode handling, filename anonymization, Git revision reporting, and splash screen stability. [full release notes] Download: BleachBit 6.0 | Portable | ~20.0 MB (Open Source) View: BleachBit Home page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • DriversCloud 12.1.6 by Razvan Serea With DriversCloud (formerly My-Config.com), you can explore your computer easily, safely and free. The application quickly scans your PC and identifies the hardware and software components. DriversCloud then establishes a list of the different drivers compatible with your OS and hardware. Download the drivers needed for the proper functioning of your computer. To detect your drivers, DriversCloud also displays a detailed summary of your hardware and software configuration, analyzes your BSOD, monitors in real-time your PC voltages and temperatures and lets you share your configuration online. Once the hardware components have been detected, you will be able to obtain with just a few clicks the latest drivers corresponding to the identified hardware. You can record your configuration on the site for free, and can get the corresponding URL to post the configuration to technical forums, e-mail and social networks. You can also download the detection result (the configuration) as a PDF file. To protect the user's privacy and data confidentiality, a 4-level confidentiality system was created that filters the XML marks and gives control to the user. The default level can be modified in the preferences. Using the maximum level will prevent the user from publishing his configuration and generating a corresponding PDF file. In non-connected mode, each XML configuration is stored on the server for one day (for practical reasons). However, you are given the opportunity to manually delete it. Created in 2004, and continually improved, My-Config.com has established itself on the web as a free service to PC users running Windows and Linux operating systems. The service is designed to work with the most common Internet browsers (Edge, Firefox, Chrome, Safari). Download: DriversCloud 64-bit | 20.0 MB (Freeware) Download: DriversCloud 32-bit | 18.9 MB Link: DriversCloud Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Month Later
      AndreaB earned a badge
      One Month Later
    • One Month Later
      agatameier earned a badge
      One Month Later
    • Week One Done
      agatameier earned a badge
      Week One Done
    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
  • Popular Contributors

    1. 1
      +primortal
      516
    2. 2
      +Edouard
      193
    3. 3
      PsYcHoKiLLa
      147
    4. 4
      ATLien_0
      96
    5. 5
      Steven P.
      77
  • Tell a friend

    Love Neowin? Tell a friend!