Strlen into a structure - structure

Hello i am trying to use a strlen function in an structure but i am failing badly.
My code is this:
after the scanf i get only the first caracter of the table and in the last print f the programm crashes.
Any suggestions or ideas what i am doing wrong?
Mainly the user will fill the table with alphanumerics and with the strlen i would like to extract the lenght of the alphanumerics.
#include<stdio.h>
#include <string.h>
main(void)
{
int M,N;
struct word_pair /*structure */
{
char word[M]; // the alphanumeric
int lenght; //the lenght of alphanumeric
};
struct word_pair word_table[N]; // the table of alphanumeric and lenght
printf("Enter a frase:");
scanf("%c",&word_table[N].word[M]);
printf("\n Your frase is %c ",word_table[N].word[M]);
printf("\n %u ",(unsigned)strlen(word_table[N].word[M]));
}

You declare an array of word_pair of but you use only one struct in the array and you store it in an invalid position(N). Take into account that when you declare an array of length n such as int a[n]; the valid positions inside the array are from 0 to n - 1.
You must first initialize the variables N and M to whatever value you need. After that, try (assuming that N > 0 and M > 0):
scanf("%c",&word_table[0].word[0]);
printf("\n Your frase is %c ",word_table[0].word[0]);
printf("\n %u ",(unsigned)strlen(word_table[0].word[0]));

Related

Can't put a space between output and input on the same line

After printing, if I write the name I get:
Insert a name :Andrea
There is no space before Andrea, even if I put the space in the output. How can I add a space before writing the name?
#include <stdio.h>
int main() {
int string[8];
printf("\nInsert a name : ");
printf(" ");
scanf("%s", string);
printf("\nThe name is : %s", string);
return 0;
}
The code that you provided does not compile because the variable string is an array of integers (and not a string as you might think). And when you input the value of it, you're telling the compiler to expect a string ("%s" in scanf("%s", string")).
Change your string declaration to char string[8] and it should work (with the spacing you want):
Note that the value that goes into string will not contain more than 8 characters.
Actually, you did a small mistake in your code, you declared the string to be an array of int & from the code scanf("%s", string") the compiler expects from the user to enter a string as it contains %s as the format specifier. Hence, the code doesn't compile.
In order to correct this, you should declare string as char string[8] (string containing 8 characters).
The correct code is given below :
#include <stdio.h>
int main() {
char string[8];
printf("\nInsert a name : ");
scanf("%s", string);
printf("\nThe name is : %s", string);
return 0;
}
From the above correction your problem for space between input and output will be solved!
Here, is the output which is received from this correction :
I hope so this explanation will be helpful for you!
If any problem persists then feel free to ask in comments! ;-)

How to put an actual variable n in printf("%nd",var) instead of any integer in C?

I'm using %nd in a loop where 'var' increments. Now i want 'n' to be the no. of digits of 'var' so that it aligns correctly
You can specify a variable as the width parameter in printfusing the * width specifier:
printf("%*d\n", digs, var);
This will use the value of the digs variable as the format width.
A simple, complete example:
#include <stdio.h>
int main()
{
for (int i = 1; i <= 10; ++i)
printf("%*d\n", i, i); // i is used both as the width specifier and the actual value printed!
}
I would do it by generating the desired format-string using sprintf() at run-time, like this:
#include <stdio.h>
int main(int, char **)
{
char formatBuf[100];
for (int i=0; i<10; i++)
{
// Note: %% specifies one literal %
// %d specifies the width-number to put in the format string
// ... and the final d is a literal 'd' to include in the format string
sprintf(formatBuf, "num=%%%dd", i);
printf("formatBuf=[%s]\n", formatBuf);
printf(formatBuf, i);
printf("\n");
}
return 0;
}
... which gives this output as a demonstration:
formatBuf=[num=%0d]
num=0
formatBuf=[num=%1d]
num=1
formatBuf=[num=%2d]
num= 2
formatBuf=[num=%3d]
num= 3
formatBuf=[num=%4d]
num= 4
formatBuf=[num=%5d]
num= 5
formatBuf=[num=%6d]
num= 6
formatBuf=[num=%7d]
num= 7
formatBuf=[num=%8d]
num= 8
formatBuf=[num=%9d]
num= 9

Implementing a side channel timing attack

I'm working on a project implementing a side channel timing attack in C on HMAC. I've done so by computing the hex encoded tag and brute forcing byte-by-byte by taking advantage of strcmp's timing optimization. So for every digit in my test tag, I calculate the amount of time it takes for every hex char to verify. I take the hex char that corresponds to the highest amount of time calculated and infer that it is the correct char in the tag and move on to the next byte. However, strcmp's timing is very unpredictable. Although it is easy to see the timing differences between comparing two equal strings and two totally different strings, I'm having difficulty finding the char that takes my test string the most time to compute when every other string I'm comparing to is very similar (only differing by 1 byte).
The changeByte method below takes in customTag, which is the tag that has been computed up to that point in time and attempts to find the correct byte corresponding to index. changeByte is called n time where n=length of the tag. hexTag is a global variable that is the correct tag. timeCompleted stores the average time taken to compute the testTag at each of the hex characters for a char position. Any help would be appreciated, thank you for your time.
// Checks if the index of the given byte is correct or not
void changeByte(unsigned char *k, unsigned char * m, unsigned char * algorithm, unsigned char * customTag, int index)
{
long iterations=50000;
// used for every byte sequence to test the timing
unsigned char * tempTag = (unsigned char *)(malloc(sizeof (unsigned char)*(strlen(customTag)+1 ) ));
sprintf(tempTag, "%s", customTag);
int timeIndex=0;
// stores the time completed for every respective ascii char
double * timeCompleted = (double *)(malloc (sizeof (double) * 16));
// iterates through hex char 0-9, a-f
for (int i=48; i<=102;i++){
if (i >= 58 && i <=96)continue;
double total=0;
for (long j=0; j<iterations; j++){
// calculates the time it takes to complete for every char in that position
tempTag[index]=(unsigned char)i;
struct rusage usage;
struct timeval start, end;
getrusage(RUSAGE_SELF, &usage);
start=usage.ru_stime;
for (int k=0; k<50000; k++)externalStrcmp(tempTag, hexTag); // this is just calling strcmp in another file
getrusage (RUSAGE_SELF, &usage);
end=usage.ru_stime;
}
double startTime=((double)start.tv_sec + (double)start.tv_usec)/10000;
double endTime=((double)end.tv_sec+(double)end.tv_usec)/10000;
total+=endTime-startTime;
}
double val=total/iterations;
timeCompleted[timeIndex]=val;
timeIndex++;
}
// sets next char equal to the hex char corresponding to the index
customTag[index]=getCorrectChar (timeCompleted);
free(timeCompleted);
free(tempTag);
}
// finds the highest time. The hex char corresponding with the highest time it took the
// verify function to complete is the correct one
unsigned char getCorrectChar(double * timeCompleted)
{
double high =-1;
int index=0;
for (int i=0; i<16; i++){
if (timeCompleted[i]>high){
high=timeCompleted[i];
index=i;
}
}
return (index+48)<=57 ?(unsigned char) (index+48) : (unsigned char)(index+87);
}
I'm not sure if it's the main problem, but you add seconds to microseconds directly as though 1us == 1s. It will give wrong results when number of seconds in startTime and endTime differs.
And the scaling factor between usec and sec is 1 000 000 (thx zaph). So that should work better:
double startTime=(double)start.tv_sec + (double)start.tv_usec/1000000;
double endTime=(double)end.tv_sec + (double)end.tv_usec/1000000;

Java: Ask user input and divide by those integers

In Java,I need to ask user input for two integers. The program needs to divide by these two integers and produce a decimal to the sixth place.
I know that i will need to name two integers: numerator and denominator. Also, I need to name a double variable: result.
Thanks for the help!!
You haven't given any clues as to the language or platform you are using, but here is a basic example written in C running on a console.
#include <stdio.h>
int main()
{
int num, den;
double quo;
printf("Enter numerator: ");
scanf("%d", &num);
printf("Enter denominator: ");
scanf("%d", &den);
if (den == 0)
printf("Divide by zero\n");
else {
quo = (double)num / (double) den;
printf("Quotient = %.6f\n", quo);
}
return 0;
}

Objective c, Scanf() string taking in the same value twice

Hi all I am having a strange issue, when i use scanf to input data it repeats strings and saves them as one i am not sure why.
Please Help
/* Assment Label loop - Loops through the assment labels and inputs the percentage and the name for it. */
i = 0;
j = 0;
while (i < totalGradedItems)
{
scanf("%s%d", assLabel[i], &assPercent[i]);
i++;
}
/* Print Statement */
i = 0;
while (i < totalGradedItems)
{
printf("%s", assLabel[i]);
i++;
}
Input Data
Prog1 20
Quiz 20
Prog2 20
Mdtm 15
Final 25
Output Via Console
Prog1QuizQuizProg2MdtmMdtmFinal
Final diagnosis
You don't show your declarations...but you must be allocating just 5 characters for the strings:
When I adjust the enum MAX_ASSESSMENTLEN from 10 to 5 (see the code below) I get the output:
Prog1Quiz 20
Quiz 20
Prog2Mdtm 20
Mdtm 15
Final 25
You did not allow for the terminal null. And you didn't show us what was causing the bug! And the fact that you omitted newlines from the printout obscured the problem.
What's happening is that 'Prog1' is occupying all 5 bytes of the string you read in, and is writing a null at the 6th byte; then Quiz is being read in, starting at the sixth byte.
When printf() goes to read the string for 'Prog1', it stops at the first null, which is the one after the 'z' of 'Quiz', producing the output shown. Repeat for 'Prog2' and 'Mtdm'. If there was an entry after 'Final', it too would suffer. You are lucky that there are enough zero bytes around to prevent any monstrous overruns.
This is a basic buffer overflow (indeed, since the array is on the stack, it is a basic Stack Overflow); you are trying to squeeze 6 characters (Prog1 plus '\0') into a 5 byte space, and it simply does not work well.
Preliminary diagnosis
First, print newlines after your data.
Second, check that scanf() is not returning errors - it probably isn't, but neither you nor we can tell for sure.
Third, are you sure that the data file contains what you say? Plausibly, it contains a pair of 'Quiz' and a pair of 'Mtdm' lines.
Your variable j is unused, incidentally.
You would probably be better off having the input loop run until you are either out of space in the receiving arrays or you get a read failure. However, the code worked for me when dressed up slightly:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char assLabel[10][10];
int assPercent[10];
int i = 0;
int totalGradedItems = 5;
while (i < totalGradedItems)
{
if (scanf("%9s%d", assLabel[i], &assPercent[i]) != 2)
{
fprintf(stderr, "Error reading\n");
exit(1);
}
i++;
}
/* Print Statement */
i = 0;
while (i < totalGradedItems)
{
printf("%-9s %3d\n", assLabel[i], assPercent[i]);
i++;
}
return 0;
}
For the quoted input data, the output results are:
Prog1 20
Quiz 20
Prog2 20
Mdtm 15
Final 25
I prefer this version, though:
#include <stdio.h>
enum { MAX_GRADES = 10 };
enum { MAX_ASSESSMENTLEN = 10 };
int main(void)
{
char assLabel[MAX_GRADES][MAX_ASSESSMENTLEN];
int assPercent[MAX_GRADES];
int i = 0;
int totalGradedItems;
for (i = 0; i < MAX_GRADES; i++)
{
if (scanf("%9s%d", assLabel[i], &assPercent[i]) != 2)
break;
}
totalGradedItems = i;
for (i = 0; i < totalGradedItems; i++)
printf("%-9s %3d\n", assLabel[i], assPercent[i]);
return 0;
}
Of course, if I'd set up the scanf() format string 'properly' (meaning safely) so as to limit the length of the assessment names to fit into the space allocated, then the loop would stop reading on the second attempt:
...
char format[10];
...
snprintf(format, sizeof(format), "%%%ds%%d", MAX_ASSESSMENTLEN-1);
...
if (scanf(format, assLabel[i], &assPercent[i]) != 2)
With MAX_ASSESSMENTLEN at 5, the snprintf() generates the format string "%4s%d". The code compiled reads:
Prog 1
and stops. The '1' comes from the 5th character of 'Prog1'; the next assessment name is '20', and then the conversion of 'Quiz' into a number fails, causing the input loop to stop (because only one of two expected items was converted).
Despite the nuisance value, if you want to make your scanf() strings adjust to the size of the data variables it is reading into, you have to do something akin to what I did here - format the string using the correct size values.
i guess, you need to put a
scanf("%s%d", assLabel[i], &assPercent[i]);
space between %s and %d here.
And it is not saving as one. You need to put newline or atlease a space after %s on print to see difference.
add:
when i tried
#include <stdio.h>
int main (int argc, const char * argv[])
{
char a[1][2];
for(int i =0;i<3;i++)
scanf("%s",a[i]);
for(int i =0;i<3;i++)
printf("%s",a[i]);
return 0;
}
with inputs
123456
qwerty
sdfgh
output is:
12qwsdfghqwsdfghsdfgh
that proves that, the size of string array need to be bigger then decleared there.