My C program prints 0xE instead of 0x0E in Keccak implementation - c

Im working on an implementation of Keccak(SHA-3) and for example I got this:
Keccak("abc") = 3A985DA74FE225B245C172D6BD390BD855F86E3E9D525B46BFE24511431532
Instead of (according: http://www.di-mgt.com.au/sha_testvectors.html)
3A985DA74FE225B2045C172D6BD390BD855F086E3E9D525B46BFE24511431532
As you can see my program miss a "0x00" and Im not sure what I am doing wrong.
Sorry guys here it is my main method code:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include "round.h"
#include "keccak.h"
#define TAM_MAX_ENTRADA 4096 /*Especificacion del numero de caracteres de la entrada*/
int main(int argc, char *argv[])
{
int32_t sha3Tipo; /*Nos dice el tipo de SHA3*/
char Mensaje[TAM_MAX_ENTRADA]; /*Array de caracteres donde guardamos el mensaje de entrada*/
printf("Elige el tamaño de salida (224,256,384,512): ");
scanf("%d",&sha3Tipo);
if(argc == 1)
{
strcat(Mensaje,""); /*Si no nos han pasado argumentos significa que es un string vacio*/
}
else
{
strcpy(Mensaje,argv[1]); /*Copiamos la primera palabra en el array de caracteres*/
}
for(int32_t i = 2; i<argc; i++)
{
strcat(Mensaje," "); /*Si tenemos mas de una palabra entonces anadimos */
strcat(Mensaje,argv[i]);
}
int32_t size = strlen(Mensaje);
int32_t *psize = &size;
uint8_t *newmessage;
newmessage=keccak((uint8_t *)Mensaje, *psize, sha3Tipo);
printf("Keccak(\"%s\") = ",Mensaje);
for(int32_t i =0; i<sha3Tipo/8; i++)
{
printf("%X", *(newmessage+i));
}
printf("\n");
return 0;
}

Perhaps you're losing the leading zeroes when converting the numbers into hexadecimal strings? For example, consider the following code:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Without formatting: %x and %x\n", 12, 99);
printf("With formatting: %02x and %02x\n", 12, 99);
return 0;
}
When run, the output is:
Without formatting: c and 63
With formatting: 0c and 63
I'm thinking that your 4 and 8 should be 04 and 08, but they are not being formatted correctly.

Related

Storing and printing a struct array doesnt work as expected

First of all, I want to explain my vocabulary of functions:
Universo: Universe
Edad: Age
Nombre: Name
Alias: Nickname
Nacionalidad: Country
Persona: Person
Insertar persona: Add Person to the Struct array
Mostrar persona: Print all the struct array elements
So I want to create a struct array and an options table in where I can choose to add persons or print them. The program max person capacity is 1000 and it checks if the person is already in the array or not, adding ir if so.
So I don't understand in first place why it doesnt print all the persons and if the persons actually are stored. Can you help me? It is a class work and I can't complicate it more that, so pointers aren't allowed. This is my code:
#include <stdio.h>
#include <stdlib.h>
#define MAX_CAD 100
#include <string.h>
#include <ctype.h>
struct persona{
char nombre[MAX_CAD];
int edad;
char nacionalidad[MAX_CAD];
char alias[MAX_CAD];
};
int insertarPersona(struct persona universo[], int capacidad_max, struct persona nueva);
void mostrarMundo(struct persona universo[], int capacidad_max);
int main()
{
int seleccion, capacidadmax=1000, i=0;
struct persona universo[1000];
struct persona nueva;
strcpy(universo[i].nombre, "-");
strcpy(universo[i].nacionalidad, "-");
strcpy(universo[i].alias, "-");
universo[i].edad = -1;
do{
printf("1-Crear persona \^\// \n");
printf("2-Mostrar universo |. .| \n");
printf("3-Thanos-Chascar _ \ - / _ \n");
printf("4-Restaurar universo \_| |_/ \n");
printf("5-Salir \ \ \n");
printf(" __/_/__\n");
printf(" | |\n");
printf(" \ /\n");
printf(" \___/\n");
scanf("%d", &seleccion);
if(seleccion==1&&i<1000){
printf("Introduzca el nombre de la persona a añadir\n");
while(getchar()!='\n');
gets(nueva.nombre);
printf("Introduzca el alias de la persona a añadir\n");
gets(nueva.alias);
printf("Introduzca la nacionalidad de la persona a añadir\n");
gets(nueva.nacionalidad);
printf("Introduzca la edad de la persona a añadir\n");
scanf("%d", &nueva.edad);
if(insertarPersona(universo, capacidadmax, nueva)==1){
strcpy(universo[i].nombre, nueva.nombre);
strcpy(universo[i].alias, nueva.alias);
strcpy(universo[i].nacionalidad, nueva.nacionalidad);
universo[i].edad=nueva.edad;
printf("Persona añadida!\n");
i++;
}
else{
printf("El universo esta lleno o dicha persona ya esta dentro\n");
}
}else if(seleccion==2){
printf("pers. Nombre\t\t\t\t\t Alias\t\t\t\t Nacionalidad\t\t\t Edad\n");
printf("=====================================================================================================================\n");
mostrarMundo(universo, capacidadmax);
}
printf("%d",i);
}while (seleccion !=5);
return 0;
}
int insertarPersona(struct persona universo[], int capacidad_max, struct persona nueva){
capacidad_max=1000;
int espersona=0;
for(int i=0; i=='\0'&& i<capacidad_max;i++){
if ((strcmp(nueva.nombre, universo[i].nombre)&& (nueva.edad!=universo[i].edad)&& strcmp(nueva.nacionalidad, universo[i].nacionalidad)&& strcmp(nueva.alias, universo[i].alias)) !=0 && i<1000){
espersona=1;
}else {
espersona=0;
}
}
return espersona;
}
void mostrarMundo(struct persona universo[], int capacidad_max){
capacidad_max=1000;
for(int i=0; i=='\0'&&i<capacidad_max; i++){
printf("%d\t%-35s%-25s\t%-20s%10d\n", i+1, universo[i].nombre, universo[i].alias, universo[i].nacionalidad, universo[i].edad);
if(universo==0){
printf("Universo no habitado\n");
}
}
}

What am I doing wrong with this array in C?

I need to know how many times does "Maria" appears in this array, but when I run it, it says that it appears 51 times, and I think its only like 8
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int g;
int i;
const char * nombres[40] = {"Sandra Marisol","Juan Luis","Perez Luis","Carlitos","Maria","Mariana", "Carlota","Anthony",
"Fernando Jan","Alfonso Roche","Julieta Zacatenco","Maria de los Angeles","Laura Jessica",
"Andrea Maria","Jose Maria","Andres Molina","Aline Derrant","Paquito","Luisa","Ana Maria",
"Caleb","Luis Fernando","Mario Alberto","Paula Monica","Otoniel","Elias Primero","Maurico Enrique",
"Anastasia Maria","Maria Juana","Juana de Arco","Aria Montgomery""Hanna Maria","Magdalena","David Green",
"Florian Drake","Edward Jones","Joakin Broder","Paar","Alicia Torres","Juan Pablo"};
for(i = 0; i>40; i++)
{
printf("%s\n", nombres[40]);
if(nombres[i] == "Maria")
g++;
}
if(g>0){
printf("El nombre de Maria aparece %d veces.", g);
}
else {
printf("El nombre de Maria NO aparece");
}
system("pause");
return 0;
}
if(nombres[i] == "Maria")
You can't compare strings like this. You need to use strstr() to look for substrings in a string.
Also,
printf("%s\n", nombres[40]); probably should have i instead of 40. And your comparison in the middle of your for loop above this is backwards.
And... probably more else wrong, but that is enough for me.
There are lots of error..... Let's see how much I could solve..xd
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int g=0;
int i;
const char * nombres[40] = {"Sandra Marisol","Juan Luis","Perez Luis","Carlitos","Maria","Mariana", "Carlota","Anthony",
"Fernando Jan","Alfonso Roche","Julieta Zacatenco","Maria de los Angeles","Laura Jessica",
"Andrea Maria","Jose Maria","Andres Molina","Aline Derrant","Paquito","Luisa","Ana Maria",
"Caleb","Luis Fernando","Mario Alberto","Paula Monica","Otoniel","Elias Primero","Maurico Enrique",
"Anastasia Maria","Maria Juana","Juana de Arco","Aria Montgomery""Hanna Maria","Magdalena","David Green",
"Florian Drake","Edward Jones","Joakin Broder","Paar","Alicia Torres","Juan Pablo"};
for(i = 0; i<40; i++)
{
printf("%s\n", nombres[i]);
if(!strcmp(nombres[i],"Maria"))
g++;
}
if(g>0){
printf("El nombre de Maria aparece %d veces.", g);
}
else {
printf("El nombre de Maria NO aparece");
}
return 0;
}
Here the counter variable g was not initialized. It should be initialized to 0 otherwize it contains some garbage value.then in for loop the condition was wrong the loop was not being executed because u write I>40 here i is initialized by 0 so condition get false and loop don't run.then printf in the loop contains nombres[40] which gives a nullpointer because you last name is hombres[39].then in if condition you can't just compare string like other variable you have to use lib function which is strcmp which means string compare.
In following conditions
strcmp(s1,s2);
**
*if s1==s2 then it returns 0.
If s1>s2 then it returns 1
If s1<s2 it returns -1
So I wrote !strcmp();
So if string matches it will return 0 and '!' Converts it to 1.
Hope this works.kudos.

Storing data in an array

I am having a problem when storing data in a structure, what happens is that when I save a name, all the names are set to the last.
I have a whole day trying to find the error.
Here the code.
#include <stdio.h>
typedef struct {
int id;
char *nombre;
int saldo;
} CLIENTES;
CLIENTES Cliente[5];
int n_client = 0;
void RegistrarCliente (char *nom, int saldo);
void Listar ();
int n_client;
void main (void)
{
for (int i = 0; i < 5; i++) {
char nombre[30];
scanf ("%s", &nombre);
RegistrarCliente (nombre, 250);
}
Listar ();
}
void RegistrarCliente (char *nom, int saldo)
{
Cliente[n_client].id = n_client;
Cliente[n_client].nombre = nom;
Cliente[n_client].saldo = saldo;
printf ("Cliente: %s registrado con una deuda de %d\n",
Cliente[n_client].nombre, Cliente[n_client].saldo);
n_client++;
}
void Listar ()
{
printf ("%-10s%-13s%-10s\n", "ID", "NOMBRE", "SALDO");
for (int i = 0; i < n_client; i++) {
printf ("%-10d%-13s%-10d\n", Cliente[i].id, Cliente[i].nombre,
Cliente[i].saldo);
}
}
Input/output
Jhosh
Cliente: Jhosh registrado con una deuda de 250
Leo
Cliente: Leo registrado con una deuda de 250
Jhonny
Cliente: Jhonny registrado con una deuda de 250
Stweart
Cliente: Stweart registrado con una deuda de 250
Carlos
Cliente: Carlos registrado con una deuda de 250
ID NOMBRE SALDO
0 Carlos 250
1 Carlos 250
2 Carlos 250
3 Carlos 250
4 Carlos 250
You have to copy the strings instead of assigning the pointer directly.
void RegistrarCliente(char * nom, int saldo)
{
Cliente[n_client].nombre = malloc(strlen(nom) + 1); /* +1 for terminating null-character */
if(Cliente[n_client].nombre == NULL)
{
perror("malloc");
return;
}
Cliente[n_client].id = n_client;
strcpy(Cliente[n_client].nombre, nom);
Cliente[n_client].saldo = saldo;
printf("Cliente: %s registrado con una deuda de %d\n", Cliente[n_client].nombre, Cliente[n_client].saldo);
n_client++;
}
Please add #include <stdlib.h> in order to use malloc() and #include <string.h> in order to use strlen() and strcpy().
As #R.Shrestha pointed out, you have to change scanf("%s", &nombre); to scanf("%s", nombre); because the former statement invokes undefined behavior for passing pointer to data having wrong type to scanf(): %s specifier calls for char*, but you passed char (*)[30].
Change this statement scanf("%s", &nombre); to scanf("%s",nombre);//it is a input of string and '&' should not be used here and use strcpy() to copy string rather than to use assignment operator...Try this

Segmentation fault in C with file

I have a segmentation fault in the moment of get the second file in the function imprimir, and i dont know whats happend, because he open and read the firts but not other file, is very confused for me, please help me
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char nombre[40];
int creditos;
float nota;
} curso;
int conteo(FILE *_entrada);
void semestre(FILE *_entrada,curso *_materias,int *_cantidad,int *_ganadas,int *_perdidas,float *_promedio);
void imprimir(curso *_materias,int *_cantidad,int *_ganadas, int *_perdidas,float *_promedio);
int main(int argc, char *argv[])
{
int ganadas=0;
int perdidas=0;
float promedio=0.0;
int cantidad=0;
char *archivoEntrada;
curso *materias;
printf("Archivo de entrada \n");
scanf("%s",archivoEntrada);
FILE *entrada;
entrada=fopen(archivoEntrada,"r");
if(entrada==NULL)
{
printf("No se logro abrir el archivo de entrada\n");
exit(EXIT_FAILURE);
}
cantidad=conteo(entrada);
printf("El numero de materias es: %d \n",cantidad);
materias=(curso *)malloc(sizeof(curso)*cantidad);
semestre(entrada,materias,&cantidad,&ganadas,&perdidas,&promedio);
imprimir(materias,&cantidad,&ganadas,&perdidas,&promedio);
free(materias);
}
int conteo(FILE *_entrada)
{
int i=0;
char auxiliar[40];
while(!feof(_entrada))
{
fgets(auxiliar,40,_entrada);
i++;
}
rewind(_entrada);
return i/3;
}
void semestre(FILE *_entrada,curso *_materias,int *_cantidad,int *_ganadas,int *_perdidas,float *_promedio)
{
int i=0;
int sumaCreditos=0;
float sumaNotas=0.0;
while(i<*_cantidad)
{
fscanf(_entrada, "%s", _materias->nombre);
fscanf(_entrada, "%d", &_materias->creditos);
sumaCreditos=sumaCreditos+(_materias->creditos);
fscanf(_entrada, "%f", &_materias->nota);
if((_materias->nota)>3.0)
{
*_ganadas=(*_ganadas)+1;
}
}
}
void imprimir(curso *_materias,int *_cantidad,int *_ganadas, int *_perdidas,float *_promedio)
{
fflush(stdin);
printf("Ganadas %d \n",*_ganadas);
printf("perdidas %d \n",*_perdidas);
printf("prom %f \n",*_promedio);
char *archivoSalida;
FILE *salida;
printf("Archivo de salida \n");
scanf("%s",archivoSalida);
salida=fopen(archivoSalida,"w");
if(salida==NULL)
{
printf("No se logro abrir el archivo de salida\n");
exit(EXIT_FAILURE);
}
//Implementacion imprimir en archivo salida.txt
}
You have
char *archivoSalida;
and then
scanf("%s",archivoSalida);
The problem here is that the pointer archivoSalida doesn't actually point anywhere special. Uninitialized local variables (like archivoSalida is) have an indeterminate value. Using them without initialization leads to undefined behavior, a very common cause of crashes.
Instead you might want to use a fixed-size array:
char archivoSalida[256];
...
scanf("%255s",archivoSalida);

Stack overflow with pointers in C

I'm new in C, and I'm trying some exercises that I found.
In one of the exercises I'm trying to use a pointer to a string (a char array), but it doesn't work. It compiles, but when is executed, it throws "stack overflow" (well, I think is an "stack overflow" because I have it in spanish).
These are the problematic lines:
//This is the variable declaration, before this, there is the "main function" declaration
char entrada[100];
char *ult=entrada;
char cantidadstr[10];
int i,j,k = 0;
int res;
scanf ("%s",entrada);
printf ("\n%s",entrada);
//Here crashes
printf ("Hola %s",ult);
while (*ult != "\0"){
//And here there's more code
Thank you in advance!!
EDIT
(I can't answer me :))
Then, I'll post a bit more of code.
When I execute, after inserting data, it throws "Violación de segmento", and google says that means Stack Overflow
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void){
char entrada[1001*11*101];
/*Asi tenemos el tamano maximo:
1001 por las 1000 posibles lineas, mas la primera
11 por el tamano maximo del numero (1 + 9 ceros), mas el espacio o salto de linea siguiente
101 por el numero de numeros por linea, mas el primero
*/
char *ult=entrada;
char cantidadstr[10];
int i,j,k = 0;
int res;
memset (entrada,'\0',1001*11*101);
scanf ("%s",entrada);
printf ("\n%s",entrada);
//poniendo ese print ahi arriba, ese me lo muestra, por tanto, el fallo esta en el puntero de debajo de esta linea
printf ("Hola %s",ult);
while (*ult != "\0"){
if(*ult == "\n"){
if(i != 0){
printf("\n");
}
i++;
j = 0;
}
else if(i != 0){
if(*ult == " "){
j++;
k=0;
res = atoi(cantidadstr);
printf("%d ",res*2);
//Este es el otro cambio que hablaba
cantidadstr[10] = '\0';
}
else if(j != 0){
cantidadstr[k] = *ult;
}
}
k++;
*ult++;
}
return 0;
}
This is the exact and full code, with comments in spanish for another forum. The size of "entrada" is big enough for any data send in the exercise. The "memset" is just added. The second comment shows where it crashes
Thank you for your quick answer!!
The code before the while loop is fine as it compiles and runs correctly(as far as i can think)
But the while loop has an error i'm not sure how it compiled in your case.
because you have written
while (*ult != "\0"){
which gives compiler error as
*ult is of type char
"\0" is of type const char*
you have to convert "\0" to '\0'
The following line:
cantidadstr[10] = '\0';
will write past the end of cantidadstr, which is definitely bad and most likely causing your stack overflow. If you want to null terminate cantidadstr, use cantidadstr[9]= '\0';. Arrays in C are zero based, not one based, so the first element of an array of size N starts at [0] and the last referenceable element is [N-1].

Resources