This code is a C program for managing a list...

August 28, 2025 at 04:37 PM

#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct{ char id[10]; double saldo; } Cliente; Cliente clienti[100]; int nrCliente = 0; // Legge clienti da file void leggiClienti(const char* nomeFile){ FILE* f = fopen(nomeFile,"r"); if(!f){ printf("Errore apertura file.\n"); return; } nrCliente = 0; while(fscanf(f,"%9s %lf", clienti[nrCliente].id, &clienti[nrCliente].saldo) == 2){ nrCliente++; } fclose(f); } // Salva clienti su file void salvaClienti(const char* nomeFile){ FILE* f = fopen(nomeFile,"w"); if(!f) return; for(int i=0;i<nrCliente;i++){ fprintf(f,"%s %.2f\n", clienti[i].id, clienti[i].saldo); } fclose(f); } // Funzione vulnerabile: aggiunge saldo, input malevolo può incrementare più del previsto void aggiungiSaldo(){ char id[10]; char input[200]; double importo; printf("Inserisci ID cliente: "); scanf("%9s", id); Cliente* c = NULL; for(int i=0;i<nrCliente;i++){ if(strcmp(clienti[i].id,id)==0){ c=&clienti[i]; break; } } if(!c){ printf("Cliente non trovato.\n"); return; } printf("Inserisci importo da aggiungere (formato numero o numero1,numero2,...): "); scanf(" %199[^\n]", input); char temp[200]; strncpy(temp,input,sizeof(temp)-1); temp[sizeof(temp)-1]=0; char* token = strtok(temp,","); while(token){ double timporto; if(sscanf(token,"%lf",&timporto)==1){ c->saldo += timporto; printf("%s %.2f\n", c->id, c->saldo); } token = strtok(NULL,","); } salvaClienti("clienti.txt"); } int main(){ leggiClienti("clienti.txt"); aggiungiSaldo(); return 0; }

This code is a C program for managing a list of clients (Cliente) and their monetary balances. It includes functionalities to read client data from a file, update their balances based on user input, and save the updated data back to the file. Here's a detailed breakdown of what the code does:


1. Structure Definition

typedef struct{
    char id[10];
    double saldo;
} Cliente;

Defines the Cliente structure, which has:

  • id — a string (max 9 characters + null terminator) representing the client's ID.
  • saldo — a double representing the client's balance.

2. Global Variables

Cliente clienti[100];
int nrCliente = 0;
  • clienti is a global array of Cliente objects with a maximum of 100 clients.
  • nrCliente keeps track of the total number of clients currently loaded into the array.

3. Read Clients from File (leggiClienti)

void leggiClienti(const char* nomeFile)

This function reads a list of clients from a file (specified by nomeFile).

  • It opens the file in read mode using fopen().
  • For each line that matches the format id saldo (e.g., JohnDoe 1000.0), it stores the client's ID and balance in the clienti array.
  • The function updates nrCliente to reflect the total number of clients read.

If the file cannot be opened, it outputs an error message.


4. Save Clients to File (salvaClienti)

void salvaClienti(const char* nomeFile)

This function saves all clients and their balances back to a file (specified by nomeFile).

  • It opens the file in write mode using fopen().
  • Writes each client's id and saldo as a line in the file, formatted as: id saldo (e.g., JohnDoe 1050.00).
  • Closes the file afterward.

5. Update Client Balance (aggiungiSaldo)

void aggiungiSaldo()

This function allows the user to add an amount to a specific client's balance.

Steps:

  1. Prompt the user to input the client ID.

    • Retrieves the user's input via scanf() and stores it in id.
    • Searches for the corresponding Cliente in the clienti array.
    • If the client is not found, outputs an error message and exits.
  2. Prompt the user to input the amount(s) to add to the balance.

    • Allows the user to specify the amount in a single value (e.g., 100.50) or as a comma-separated list (e.g., 50.0,25.5,10.0).
    • Reads the input into the input buffer.
  3. Parse and process the input.

    • Uses strtok() to split the input string by commas.
    • Attempts to convert each token into a double amount using sscanf().
    • Adds the parsed amount to the client's saldo.
  4. Save the updated clients back to the file using salvaClienti().


6. Main Function

int main(){
    leggiClienti("clienti.txt");
    aggiungiSaldo();
    return 0;
}

The main function performs these steps:

  1. Reads the client data from the file clienti.txt into memory by calling leggiClienti("clienti.txt").
  2. Calls aggiungiSaldo() to allow the user to add amounts to a client.
  3. Exits the program.

Potential Vulnerabilities / Issues

  1. Vulnerable Input Handling in aggiungiSaldo()

    • The program uses strtok() to parse the user input from input. If malformed input or extremely large input is entered, this might lead to unexpected behavior or errors.
    • The scanf() function reads user input, but no bounds checking is performed beyond the array size limit, which could still lead to issues with user-provided values.
  2. Array Bounds Not Checked

    • Adding an excessive number of clients might overflow the clienti array, since its size is limited to 100 elements (clienti[100]).
  3. No Concurrency Control

    • If multiple instances of the program are running simultaneously, they might overwrite each other's data when reading and writing to clienti.txt.
  4. Floating Point Precision

    • Adding very small amounts repeatedly might lead to precision errors due to the limitations of floating-point representation.

Summary of What This Code Does

The code manages a list of clients stored in a text file (clienti.txt). It allows you to:

  • Load clients and their monetary balances from the file.
  • Update a specific client’s balance by adding one or more amounts.
  • Save the updated data back to the same file.

However, the program has some potential issues with input handling and lacks safeguards against errors or unintended behavior.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node