_chsize raises assertation error on visual studio 2017 - c

#include <stdio.h>
#include <stdlib.h>
...
int function () {
FILE *f;
f = fopen("list.txt", "rb+");
...
int value;
if (_chsize_s(f, value) == 0) return 1;
}
For some reason, the above snippet of code, when run in MS Visual Studio, generates an error at the _chsize_s() function. The following message pops up:
Debug Assertation Failed!
Expression: (fh >= 0 && (unsigned)fh < (unsigned)_nhandle)
I have no idea what to make of this, much less how to fix it. Any help would be much appreciated.

You are ignoring the compiler's warnings or have them disabled. In order to fix the implicit declaration warning, you must include the header for _chsize_s:
#include <io.h>
This will fix the implicit declaration warning, and uncover the error, that _chsize_s is being called with the wrong type. The correct way to call it is:
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
...
int function(void) {
FILE *f;
f = fopen("list.txt", "rb+");
...
int value;
if (_chsize_s(_fileno(f), value) == 0) return 1;
}
This shows how important it is not to ignore compiler warnings (with exceptions... most sane people will define _CRT_SECURE_NO_WARNINGS when writing C with MSVC).

Related

Cannot capture keystrokes in C [Ubuntu 16.04LTS]

I've been trying to make a keylogger on Ubuntu 16.04LTS for a while now, and this is what I have so far:
#include <stdio.h>
#include <fcntl.h>
#include <linux/input.h>
#include <stdbool.h>
int main()
{
char devname[] = "/dev/input/event0";
int device = open(devname, O_RDONLY);
struct input_event ev;
bool logging = true;
while(logging)
{
if (read(device,&ev, sizeof(ev)) >= 0){
printf("Key: %i State: %i Type: %i\n",ev.code,ev.value,ev.type);
}
}
}
However when I compile and run it (gcc), it does not output anything!
I've tried every device listed in /dev/input/by-id andthensome,but nothing seems to work.
When I compile the code using GCC, I get the warning:
keylogger.c: In function ‘main’:
keylogger.c:15:7: warning: implicit declaration of function ‘read’ [-Wimplicit-function-declaration]
if (read(device,&ev, sizeof(ev)) >= 0){
^
Which I have no idea if this has to do with the functionality of the program.
Any help is appreciated! Thanks!
I figured it out, it was a simple matter of not having superuser permissions. I excecuted the file using sudo and now everything is fine.

expected ')' before '*' token, can't seem to find error

So whenever I try to run my Makefile on my server, it always gives me the error is "Memory.c: 9 error: expected ')' before '*' token. But when I try to run it on my own computer, it works just fine. I've been trying to figure out what is wrong but can't seem to find it.
I've attached the 3 files that are used in this part of my program. Memory.c, Memory.h and ProcessInput.h.
This is Memory.c
/* Initializes memory */
#include <stdio.h>
#include <stdlib.h>
#include "memory.h"
void initializeMemory(memory** memArray, int memSize)
{
// Allocating space for memory array
*memArray = malloc(memSize * sizeof(memory));
if(*memArray == NULL)
{
fprintf(stderr, "Error allocating space for array of memory" );
exit(1); // exit(1) = Unsuccessful exit
}
// Initializing the contents within memory array
int i = 0;
for(i = 0; i < memSize; i ++)
{
((*memArray)[i]).occupied = false;
}
}
and this is Memory.h
// Definitions for Memory.c
#define bool int
#define true 1
#define false 0
#include "ProcessInput.h"
// Include guards to prevent redefinition of struct
#ifndef MEMORY_H
#define MEMORY_H
typedef struct memoryDetail
{
process process;
bool occupied;
} memory;
#endif
// Function declaration for memory.c
void initializeMemory(memory** memArray, int memSize);
the only thing used from ProcessInput.h is the process structure defined in ProcessInput.h
This is ProcessInput.h
// Include guards to prevent redefinition of struct
#ifndef PROCESSDETAIL_H
#define PROCESSDETAIL_H
typedef struct processDetail
{
int timeCreated;
int processID;
int memorySize;
int jobTime;
} process;
#endif
// function declarations for ProcessInput.c
void processInput(int* maxSize, int* count, process** processes, char* fileName);
I'm not too sure why it's giving me the error. I don't know where I'm supposed to be putting a missing right brace. Any advice is much appreciated!
edit: As informed, these are the following questions that I looked at but to not avail.
error: expected ‘)’ before ‘*’ token
Multiple of same error while compiling "error: expected ')' before '*' token
http://www.dreamincode.net/forums/topic/288956-error-expected-before-token/
thanks everyone for the help!
#include "memory.h" is different to #include "Memory.h" (i.e. C is case sensitive)
If you tried #include "myfile.h" instead of #include "MyFile.h" the error may be more obvious. In this case it just happens that the compiler finds the system memory.h.
<memory.h> is a header from C library of pre-standard era. It is quite possible that your standard library still provides it and the compiler takes that one instead of yours.
Try renaming your header file and see if it changes anything.

Setting Immutable Flag using ioctl() in C

I have attempted to make a script that creates a file and then sets it as immutable similar to the chattr +i command for linux. The script compiles (with gcc), runs and the file is created. However the file itself is not immutable and can be removed with a simple rm -f. I have attempted to stacktrace where chattr is called and I found a function called ioctl. I then used what little information I could gather and came up with what I have below. I narrowed it down from ext2_fs.h but it just doesn't seem to work. I've clearly overlooked something.
Updates to previous entry: Compiles but returns -1 on ioctl() function. Bad address shown with perror().
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
int main()
{
FILE *fp;
char shovel[16] = "I have a shovel!";
fp = fopen("/shovel.txt", "w+");
fwrite(shovel, sizeof(shovel[0]), sizeof(shovel)/sizeof(shovel[0]), fp);
ioctl(fileno(fp), FS_IOC_SETFLAGS, 0x00000010);
fclose(fp);
}
Any help appreciated.
You are using the right ioctl command, but you're passing it the wrong arguments.
The manpage for ioctl_list(2) shows that FS_IOC_SETFLAGS expects to receive a pointer to int (an int *), yet you're passing it an integer literal (hence the Bad Address error).
The fact that you don't to any error checking whatsoever is also not helping.
The correct flag to pass to FS_IOC_SETFLAGS is a pointer holding the value EXT2_IMMUTABLE_FL, which is defined in ext2fs/ext2_fs.h (some older / different Linux distributions seem to have it under linux/ext2_fs.h), so you'll need to #include <ext2fs/etx2_fs.h>. Make sure to install e2fslibs-dev (and probably you'll need linux-headers too).
This code is working:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
#include <ext2fs/ext2_fs.h>
int main()
{
FILE *fp;
char shovel[16] = "I have a shovel!";
if ((fp = fopen("shovel.txt", "w+")) == NULL) {
perror("fopen(3) error");
exit(EXIT_FAILURE);
}
fwrite(shovel, sizeof(shovel[0]), sizeof(shovel)/sizeof(shovel[0]), fp);
int val = EXT2_IMMUTABLE_FL;
if (ioctl(fileno(fp), FS_IOC_SETFLAGS, &val) < 0)
perror("ioctl(2) error");
fclose(fp);
return 0;
}
Remember to run this as root.
UPDATE:
As Giuseppe Guerrini suggests in his answer, you might want to use FS_IMMUTABLE_FL instead, and you won't need to include ext2_fs.h:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
int main()
{
FILE *fp;
char shovel[16] = "I have a shovel!";
if ((fp = fopen("shovel.txt", "w+")) == NULL) {
perror("fopen(3) error");
exit(EXIT_FAILURE);
}
fwrite(shovel, sizeof(shovel[0]), sizeof(shovel)/sizeof(shovel[0]), fp);
int val = FS_IMMUTABLE_FL;
if (ioctl(fileno(fp), FS_IOC_SETFLAGS, &val) < 0)
perror("ioctl(2) error");
fclose(fp);
return 0;
}
The main problem is that the ioctl wants a pointer to the mask, not a direct constant. You have to define a int variable, store the mask (0x10) in it and pass its address as third argument of ioctl.
Also, I'd add some hints:
other programs to change attributes are used to use low-level I/O directly (open, close...). Also, the file is usually opened with O_RDONLY.
Use FS_IMMUTABLE_FL istead the raw constant.
Get the current attribute mask first (FS_IOC_SETFLAGS) and mask it with the new flag, so other settings are not lost by the service.

Multiple definition and file management

I'm writing a program for vocabulary training, for myself. And the program itself should be available in different languages, atm in German and English.
What I want is to have a main file which manage all and two separate files for the functions in the right language.
I compile all the files with:
gcc vocTrainer.c german_menue.c english_menue.c -o v.exe
But I get an error of multiple definition even though I only include one of the language files depending on your input.
Multiple defintion of 'orderOfVoc'
First defined here: collect2.exe error: ld returned 1 exit status
My code:
vocTrainer.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "german_menue.h"
#include "english_menue.h"
int main(void)
{
char selectLang[1]; //store 1 for English or 2 for German
system("cls"); //clear screen
memset(selectLang,0,1); //set all fields in the array to 0
while(selectLang[1] != 1 && selectLang[1] != 2)
{
//select your language
printf("Choose language - Sprache auswaehlen:\n(1) - Englisch/English\n(2) - Deutsch/German\n");
scanf("%d",&selectLang[1]);
system("cls");
}
//language query
if(selectLang[1] == 2)
{
#include "german_menue.c"
}
else
{
#include "english_menue.c"
}
printf("Test of select Order: %d",orderOfVoc());
return 0;
}
german_menue.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "german_menue.h"
int orderOfVoc()
{
char selectOrder[1]; /*store the choosen order of vocabulary.
1 for one after another 2 for a random sequence of words*/
printf("Wie sollen die Vokabeln abgefragt werden?\n(1) - Der Reihe nach\n(2) - Zufaellig\n");
scanf("%d",&selectOrder[1]);
return selectOrder[1];
}
english_menue.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "german_menue.h"
int orderOfVoc()
{
char selectOrder[1]; /*store the choosen order of vocabulary.
1 for one after another 2 for a random sequence of words*/
printf("How do you want to learn the vocabulary?\n(1) - Vocabulary in order\n(2) - Random order\n");
scanf("%d",&selectOrder[1]);
return selectOrder[1];
}
german_menue.h
#ifndef GERMAN_MENUE_H //include guards
#define GERMAN_MENUE_H
extern int orderOfVoc();
#endif //GERMAN_MENUE_H
english_menue.h
#ifndef ENGLISH_MENUE_H //include guards
#define ENGLISH_MENUE_H
extern int orderOfVoc();
#endif //ENGLISH_MENUE_H
Primary Issue: In your code,
if(selectLang[1] == 2)
{
#include "german_menue.c"
}
else
{
#include "english_menue.c"
}
is not doing what you're thinking. There are may issues, like
#include is compile time operation (during preprocessing state) and essentially cannot be controlled at runtime.
You don't include source files. You compile and link them together. Your compilation statement looks correct. Just leave out the above mentioned code snippet from your code.
Just to add a bit detail regarding the reason behind the error you received, is because, you have #includeed the source files (which is essentially adding the source code of that .c file in vocTrainer.c file itself) and again, at compile time, you're putting the .c files. Thus, after compilation, at linking state, compiler sees more than one occurrences of orderOfVoc() which is why compiler is complaining.
Solution:
You remove different definition of orderOfVoc() function. Make use of the user selected value. Pass the value to the orderOfVoc() as an argument, and execute accordingly.
Secondary Issue(s): Apart from above issue(s), in your code, with a definition like
char selectLang[1];
writing
scanf("%d",&selectLang[1]);
is wrong, because
selectLang[1] is out of bound access. Array index in C starts from 0.
%d is not the correct formart specifier for char.
FWIW, char selectLang[1]; is functionally equivalent with char selectLang;
A modified version (not tested) for aforesaid approach:
select_menue.h
#ifndef SELECT_MENUE_H //include guards
#define SELECT_MENUE_H
//according to {store 1 for English or 2 for German}
#define ENGLISH 1
#define GERMAN 2
extern int orderOfVoc(int);
#endif //SELECT_MENUE_H
select_menue.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "select_menue.h"
int orderOfVoc(int lang)
{
int selectOrder = 0;
switch (lang)
{
case ENGLISH:
printf("How do you want to learn the vocabulary?\n(1) - Vocabulary in order\n(2) - Random order\n");
scanf("%d",&selectOrder); //add possible error check
break;
case GERMAN:
printf("Wie sollen die Vokabeln abgefragt werden?\n(1) - Der Reihe nach\n(2) - Zufaellig\n");
scanf("%d",&selectOrder); //add possible error check
break;
}
return selectOrder;
}
vocTrainer.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "select_menu.h"
int main(void)
{
int selectLang = 0; //array not required, initialize in single statement
//store 1 for English or 2 for German
while(selectLang != 1 && selectLang != 2)
{
//select your language
printf("Choose language - Sprache auswaehlen:\n(1) - Englisch/English\n(2) - Deutsch/German\n");
scanf("%d",&selectLang);
}
printf("Test of select Order: %d",orderOfVoc(selectLang));
return 0;
}
#include is a preprocessor directive that includes the contents of the file named at compile time.
The code that conditionally includes stuff is executed at run time...not compile time. So both files are being compiled in. ( You're also including each file twice, once in the main function and once above it, which is just confusing and probably wrong, but we'll ignore that for now. )
You can't really conditionally include stuff at run time. You can use other preprocessor directives (#ifdef, etc. ) to conditionally include one or the other file at compile time, but for your purposes you really need to have some sort of global flag that each function in the included files uses to determine if it should display english or german, etc.
Internationalization of strings is a whole topic in itself. There are lots of ways to handle it, and some libraries to make it easier depending on your platform.
Here's one way you could handle the same scenari:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "german_menue.h"
char *getLocalizedString(int stringId)
{
// Pseudo-Code, not real C++
// Also ignores memory issues and deallocating strings when done
char *localizedString = LoadGermanOrEnglishStringBasedOnGlobalVarForLanguage(stringId);
return localizedString ;
}
int orderOfVoc()
{
int stringId = 1;//should be constant for this message
char *localizedString = getLocalizedString(stringId);
printf("%s", localizedString);
scanf("%d",&selectOrder[1]);
return selectOrder[1];
}

Unstable output when using icc

I would like to report an intriguing bug I have. The piece of code below is supposed to print out 20 times "1.0". Instead, when compiling with icc (11.1) on my mac (snow leopard 10.6.8), I get unstable values (16 times "0.0" then 4 times "1.0"). I make use of several features in the code but none of them seems to have a bad syntax (no error during compilation, and valgrind reports no error during running). However if I change anything (even non used function - that's why I find it very strange), I get the correct output. Compiling with gcc gives the correct output as well.
But I think the strangest thing is that if I delete the function "function1", the bug disappears, although the function is NOT used in the code.
This is really odd, and now I fear that my code (which is much bigger than that) will be unstable. I need your help, I'm really puzzled by this. Is there anything wrong in the syntax?
main.c:
#include "main.h"
int main(argc,argv)
int argc;
char **argv;
{
Config para;
para.option1 = ONE;
para.a[0] = 0.0;
para.a[1] = 0.0;
para.a[2] = 0.0;
para.a[3] = 1.0;
int i;
double *x = (double *)malloc(20*sizeof(double));
for(i=0;i<20;i++) x[i] = 1.0;
for(i=0;i<20;i++) printf("%f \n", x[i]);
free(x);
function2(para);
return EXIT_SUCCESS;
}
void function1(int option){
switch(option){
case ONE: case TWO: case THREE: case MONE:
printf("MONE to THREE\n");
break;
case FOUR:
printf("FOUR\n");
break;
}
return;
}
void function2(const Config para){
if(para.option1 == FOUR){
printf("FOUR\n");
}
return;
}
main.h:
#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <stdarg.h>
#define MONE -1
#define ONE 1
#define TWO 2
#define THREE 3
#define FOUR 4
typedef struct Config
{
int option1, option2;
double a[4];
} Config;
void function1(int option);
void function2(const Config para);
When digging more on the web, I found this bug report from Intel:
http://software.intel.com/en-us/articles/intel-compiler-and-xcode-322-linker-runtime-crash-with-switch-statement/
It seems to be related to how the icc compiler optimizes case statements. Their suggestions to solve the problem are the following:
1) Use Xcode 3.2.1 with 11.1 compiler.
2) Use 11.1 compiler with the option -use-asm with Xcode 3.2.2, 3.2.3, 3.2.4.
It should fix most cases but there are some cases when even generating object file through external assembler L* symbols still may appear in object file. Those cases are usually constant string literals placed in cstring section
3) Use Intel Composer XE.
My Xcode is version 3.2.6, but solution 2) solved my problem. I remain however quite puzzled about this (and the lack of documentation on the web).
Thanks.

Resources