how to create a union - c

I made a mistake while using union,and I don't know why.
the problem is in the function goto_xy();
I read it from the book, but it cannot be compiled.
In this function I am trying to locate the cursor, but REGS variable is not declared. I want to know what is its function.
#include<stdio.h>
#include<windows.h>
#include<dos.h>
#include<conio.h>
void goto_xy(int x,int y); //goto is a key word;define the subfunction to creat the original cursor int the coordinate system
void rectangle_clear(int x1,int x2,int y1,int y2); //define the rectangle_clear opening subfunction
void center_clear(int x1,int x2,int y1,int y2); //define the center_clear opening subfunction
void creat(); //define the subfunction of creating the star
int main() //the main function
{
creat();
getch();
center_clear(0,25,0,79);
getch();
}
void center_clear(int x1,int x2,int y1,int y2) //the subfunction which creats the stars while opening the project
{
int x00,y00,x0,y0,i,d;
if((y2-y1)>(x2-x1))
{
d=(x2-x1)/2;
x0=(x1+x2)/2;
y0=y1+d;
y00=y2-d;
for(i=0;i<(d+1);i++)
{
rectangle_clear((x0-i),(x00+i),(y0-i),(y00+i));
}
delay(10); //to delay the dismis of the star
}
else
{
d=(y2-y1)/2;
y0=(y1+y2)/2;
x0=x1+d;
x00=x2-d;
for(i=0;i<d+1;i++)
{
rectangle_clear((x0-i),(x00+i),(y0-i),(y00+i));
}
delay(10);
}
}
void rectangle_clear(int x1,int x2,int y1,int y2) //to creat the star int the shape of a rectangle
{
int i,j;
for(i=y1;i<y2;i++)
{
goto_xy(x1,i);
putchar(' ');
goto_xy(x2,i);
putchar(' ');
delay(10);
}
for(j=x1;j<x2;j++)
{
goto_xy(i,y1);
putchar(' ');
goto_xy(i,y2);
putchar(' ');
delay(10);
}
}
void goto_xy(int x,int y)
{
union REGS r;
r.h.ah=2;
r.h.dl=y;
r.h.dh=x;
r.h.bh=0;
int86(0x10,&r,&r);
}
void creat()
{
int i,j;
for(i=0;i<24;i++)
{
for(j=0;j<79;j++)
{
goto_xy(i,j);
printf("a");
}
}
}

It mostly appears to me that the union REGS must be already present in one of the header files and you are including the same.
As can be seen from your code below, even the members of union like h and the members of h are also present, which means the union is there in some header file and you are including it.
void goto_xy(int x,int y)
{
union REGS r;
r.h.ah=2; //Here you are accessing the member of REGS and even the sub-members of h
r.h.dl=y;
r.h.dh=x;
r.h.bh=0;
int86(0x10,&r,&r);
}
EDIT:
A Google search tells me that UNION REGS will be defined in dos.h and it is some like
union REGS {
struct WORDREGS x;
struct BYTEREGS h;
};
So, you need to include dos.h to solve your problem. But, it appears inspite of you including that, this problem is present. You can as well open dos.h and check if union REGS is present or not.
See here for more details.

To define a union, you need to do the following:
union REGS { some_type h; other_type f; };
Now you can create a variable of type REGS and use the union.

Related

Call function with arra out of bounds access

so I've got a buggy C file in which i need to find an exploit. I have found a bug when accessing the following struct:
#define BOARD_SIZE 10
typedef int (*turn_function_t)(struct board *);
typedef void (*win_function_t)(struct board *);
struct board {
uint8_t f1[BOARD_SIZE][BOARD_SIZE];
uint8_t f2[BOARD_SIZE][BOARD_SIZE];
win_function_t win;
turn_function_t turn;
int avail;
};
int do_shot(struct board *board, int strength, int x, int y) {
if(!(x >= 0 && x <= BOARD_SIZE && y >= 0 && y <= BOARD_SIZE)) {
return SHOT_ERR_EINVAL;
}
/* If there was already a sunken ship, return error */
if(board->f1[x][y] && !board->f2[x][y])
return SHOT_ERR_SUNKEN;
/* Now perform shot */
if(!board->f2[x][y])
return SHOT_WATER;
board->f2[x][y] -= strength;
if(!board->f2[x][y])
return SHOT_SUNKEN;
return SHOT_HIT;
}
The bug I found is a wrong index check when accessing array f2. I can chose the index as input (index can be anything from 0 to 10 inclusive). I need to find a way to call the function win (doesn't matter which parameter). My question now is is there any way I can use that out of bounds access to call the function win since the function pointer is stored directly after the array f2 inside the struct?
of cause it can be done easily.
I show you an example code below.
I use pragma pack(1) for byte align and use print to find the address of the function, and finally I got it.
the code may can not be run on your computer.
but your can find the address by print to make bounds address equal to function address.
it may be f[0][-1] on your computer
#include <stdio.h>
typedef int (*turn_function_t)(struct board *);
#pragma pack(1)
struct board
{
turn_function_t win;
int f[10][10];
};
#pragma pack(0)
int win(struct board *b)
{
printf("Win!\n");
return 0;
}
int main()
{
struct board b;
b.win = win;
// printf("%p\n", &b.f[0][-2]);
// printf("%p\n", &b.win);
(*(turn_function_t *)(&b.f[0][-2]))(&b);
return 0;
}

how can i access a variable in enum

#define NUMBER_OF_CARDS 54
typedef enum type{
QUEEN;
JACK;
KING
} CardTypes;
typedef struct game{
CardTypes cards[NUMBER_OF_CARDS];
struct{
int hearts;
int spades;
int clubs;
int diamonds;
}
int players_cards;
}GameState;
I have something similar like this and I want to access any variable from enum when this function is called
void set_cards(GameState gamestate, int x, int y, CardTypes cardtypes){
gamestate.cards[x * y] = cardtypes;
}
void generate_game(GameState gamestate){
/*
some code
*/
if(variable == 0){
set_cards(gamestate, x, y, gamestate.cards[NUMBER_OF_CARDS].JACK;
//This is what I have tried but it doesn't work
I hope you understand what I mean, because I really don't know how to explain this any better.
set_cards(gamestate, x, y, gamestate.cards[NUMBER_OF_CARDS].JACK;
//this is what I have tried but it doesn't work
please ignore any inaccuracies in the code. what is important for me is how can i access any of the enum's variable in the function generate_game().
this right here: if(variable == 0){ set_cards(gamestate, x, y, gamestate.cards[NUMBER_OF_CARDS].JACK; //This is what I have tried but it doesn't work
Based upon what #Aconcagua wrote your code should be using pointers :
// gamestate is a structure , so it must be passed as pointer to enable modification to be seen by caller
void set_cards(GameState *gamestate, int x, int y, CardTypes cardtypes){
gamestate->cards[x * y] = cardtypes;
}
void generate_game(GameState *gamestate){ // here also pointer so caller know the changes
/*
some code
*/
if(variable == 0){
// next depends on what you intend to do :
// 1- set the current games rate card with value of last card
set_cards(gamestate, x, y, gamestate->cards[NUMBER_OF_CARDS-1]);
// 2- set the current gamestate to JACK
set_cards(gamestate, x, y, JACK);
Your types do not have too much sense. Card is defined by its colour and type.
typedef enum {
QUEEN,
JACK,
KING,
//you neeed some more
} CardTypes;
typedef enum {
HEART,
SPADE,
CLUB,
DIAMOND,
} CardColour;
typedef struct
{
CardTypes type;
CardColur colour;
}Card;
Card deck[54];
How to access:
void foo(Card *card)
{
Card card1;
card1.colour = HEART;
card1.type = JACK;
card -> colour = DIAMOND;
card -> type = KING;
card[34].colour = CLUB;
card[34].type = QUEEN;
}

What's wrong with my code that prints structure information?

#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <ctype.h>
struct ALUMNO{
int cod;
char nombre[20], grupo[3], app[20], apm[20];
float prom,cali[5];
} al[20]={'\0'};
void gotoxy(int x,int y){
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y= y;
SetConsoleCursorPosition(hcon,dwPos);
}
int main()
{
char gru[3];
int x = 0, sw, ac;
al[0].cod=12345;
strcpy(al[0].grupo,"1A");
strcpy(al[0].nombre,"Erick");
strcpy(al[0].app,"Medina");
strcpy(al[0].apm,"Ramirez");
al[0].prom=0.0;
al[1].cod=12346;
strcpy(al[1].grupo,"1A");
strcpy(al[1].nombre,"Emmanuel");
strcpy(al[1].app,"Sauceda");
strcpy(al[1].apm,"Perez");
al[1].prom=0.0;
al[2].cod=12347;
strcpy(al[2].grupo,"1B");
strcpy(al[2].nombre,"Vincio");
strcpy(al[2].app,"Lopez");
strcpy(al[2].apm,"Martinez");
al[2].prom=0.0;
//salon B
al[3].cod=12348;
strcpy(al[3].grupo,"1B");
strcpy(al[3].nombre,"Bryan");
strcpy(al[3].app,"Osuna");
strcpy(al[3].apm,"Beltran");
al[3].prom=0.0;
al[4].cod=12349;
strcpy(al[4].grupo,"1C");
strcpy(al[4].nombre,"Fullano");
strcpy(al[4].app,"Mangano");
strcpy(al[4].apm,"Centenario");
al[4].prom=0.0;
al[5].cod=12350;
strcpy(al[5].grupo,"1C");
strcpy(al[5].nombre,"Chapo");
strcpy(al[5].app,"Guzman");
strcpy(al[5].apm,"Loera");
al[5].prom=0.0;
//done
printf("Grupo: ");
scanf("%s",&gru);
gru[1]=toupper(gru[1]);
system("cls");
printf("Codigo\tAp.paterno\tap.materno\tnombre\tpromedio");
for (x=0, sw=0; x<25 && al[x].cod!=0; x++){
if (strcmp(gru,al[x].grupo)==0){
sw=1;
ac++;
}
if (sw==1){
gotoxy(1,ac);
printf("%i",al[x].cod);
gotoxy(12,ac);
printf("%s",al[x].app);
gotoxy(30,ac);
printf("%s",al[x].apm);
gotoxy(50,ac);
printf("%s",al[x].nombre);
gotoxy(60,ac);
printf("%.2f",al[x].prom);
}
}
ac=0;
}
For some reason, when you type in the correct group and hit enter, it will print maternal last names on top of others. Or some names maybe missing, or it's just my compiler. It works fine when you only have one name per group.
Your gru variable is used wrong in scanf. Should be gru, not &gru.
By the way, don't use scanf, use fgets

CUDA local array initalization modifies program output

I have a program which (for now) calculates values of two functions in random points on GPU , sends these values back to host, and then visualizes them. This is what I get, some nice semi-random points:
Now, if I modify my kernel code, and add the local array initalization code at the very end,
__global__ void optymalize(curandState * state, float* testPoints)
{
int ind=blockDim.x*blockIdx.x+threadIdx.x;
int step=blockDim.x*gridDim.x;
for(int i=ind*2;i<NOF*TEST_POINTS;i+=step*2)
{
float* x=generateX(state);
testPoints[i]=ZDT_f1(x);
testPoints[i+1]=ZDT_f2(x);
}
//works fine with 'new'
//float* test_array=new float[2];
float test_array[2]={1.0f,2.0f};
}
I get something like this everytime:
Does anyone know the cause of this behavior? All the drawn points are computed BEFORE test_array is initialized, yet they are affected by it. It doesn't happen when I initialize test_array before the 'for' loop.
Host/device code:
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include "curand_kernel.h"
#include "device_functions.h"
#include <random>
#include <iostream>
#include <time.h>
#include <fstream>
using namespace std;
#define XSIZE 5
#define TEST_POINTS 100
#define NOF 2
#define BLOCK_COUNT 64
#define THR_COUNT 128
#define POINTS_PER_THREAD (NOF*TEST_POINTS+THR_COUNT*BLOCK_COUNT-1)/(THR_COUNT*BLOCK_COUNT)
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, char *file, int line, bool abort=false)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
__device__ float g(float* x)
{
float tmp=1;
for(int i=1;i<XSIZE;i++)
tmp*=x[i];
return 1+9*(tmp/(XSIZE-1));
}
__device__ float ZDT_f1(float* x)
{
return x[0];
}
__device__ float ZDT_f2(float* x)
{
float gp=g(x);
return gp*(1-sqrtf(x[0]/gp));
}
__device__ bool oneDominatesTwo(float* x1, float* x2)
{
for(int i=0;i<XSIZE;i++)
if(x1[i]>=x2[i])
return false;
return true;
}
__device__ float* generateX(curandState* globalState)
{
int ind = threadIdx.x;
float x[XSIZE];
for(int i=0;i<XSIZE;i++)
x[i]=curand_uniform(&globalState[ind]);
return x;
}
__global__ void setup_kernel ( curandState * state, unsigned long seed )
{
int id = blockDim.x*blockIdx.x+threadIdx.x;
curand_init ( seed, id, 0, &state[id] );
}
__global__ void optymalize(curandState * state, float* testPoints)
{
int ind=blockDim.x*blockIdx.x+threadIdx.x;
int step=blockDim.x*gridDim.x;
for(int i=ind*2;i<NOF*TEST_POINTS;i+=step*2)
{
float* x=generateX(state);
testPoints[i]=ZDT_f1(x);
testPoints[i+1]=ZDT_f2(x);
}
__syncthreads();
//float* test_array=new float[2];
//test_array[0]=1.0f;
//test_array[1]=1.0f;
float test_array[2]={1.0f,1.0f};
}
void saveResultToFile(float* result)
{
ofstream resultFile;
resultFile.open ("result.txt");
for(unsigned int i=0;i<NOF*TEST_POINTS;i+=NOF)
{
resultFile << result[i] << " "<<result[i+1]<<"\n";
}
resultFile.close();
}
int main()
{
float* dev_fPoints;
float* fPoints=new float[NOF*TEST_POINTS];
gpuErrchk(cudaMalloc((void**)&dev_fPoints, NOF * TEST_POINTS * sizeof(float)));
curandState* devStates;
gpuErrchk(cudaMalloc(&devStates,THR_COUNT*sizeof(curandState)));
cudaEvent_t start;
gpuErrchk(cudaEventCreate(&start));
cudaEvent_t stop;
gpuErrchk(cudaEventCreate(&stop));
gpuErrchk(cudaThreadSetLimit(cudaLimitMallocHeapSize, 128*1024*1024));
gpuErrchk(cudaEventRecord(start, NULL));
setup_kernel<<<BLOCK_COUNT, THR_COUNT>>>(devStates,unsigned(time(NULL)));
gpuErrchk(cudaDeviceSynchronize());
gpuErrchk(cudaGetLastError());
optymalize<<<BLOCK_COUNT,THR_COUNT>>>(devStates, dev_fPoints);
gpuErrchk(cudaDeviceSynchronize());
gpuErrchk(cudaGetLastError());
gpuErrchk(cudaMemcpy(fPoints, dev_fPoints, NOF * TEST_POINTS * sizeof(float), cudaMemcpyDeviceToHost));
gpuErrchk(cudaEventRecord(stop, NULL));
gpuErrchk(cudaEventSynchronize(stop));
float msecTotal = 0.0f;
cudaEventElapsedTime(&msecTotal, start, stop);
cout<<"Kernel execution time: "<<msecTotal<< "ms"<<endl;
saveResultToFile(fPoints);
system("start pythonw plot_data.py result.txt");
cudaFree(dev_fPoints);
cudaFree(devStates);
system("pause");
return 0;
}
Plot script code:
import matplotlib.pyplot as plt;
import sys;
if len(sys.argv)<2:
print("Usage: python PlotScript <filename>");
sys.exit(0);
path=sys.argv[1];
x=[]
y=[]
with open(path,"r") as f:
for line in f:
vals=line.strip().split(" ");
x.append(vals[0]);
y.append(vals[1]);
plt.plot(x,y,'ro')
plt.show();
The basic problem was in code you originally didn't show in your question, specifically this:
__device__ float* generateX(curandState* globalState)
{
int ind = threadIdx.x;
float x[XSIZE];
for(int i=0;i<XSIZE;i++)
x[i]=curand_uniform(&globalState[ind]);
return x;
}
Returning an address or reference to a local scope variable from a function results in undefined behaviour. It is only valid to use x by reference or value within generateX while it is in scope. There should be no surprise that adding or moving other local scope variables around within the kernel changes the kernel behaviour.
Fix this function so it populates an array passed by reference, rather than returning the address of a local scope array. And pay attention to compiler warnings - there will have been one for this which should have immediately set off alarm bells that there was something wrong.

Accessing the Static member

I have declared the one static member inside the static method. like as follws:
static void temp1(param..){
static gint x,y ;
#TODO what you needed
values get changed here for x,y;
}
And I want to access this Two in other static method within the same file.
static void temp2 ( param .......){
accessing the x,y
}
How should I do it..? I don't want to declare public member and also don't want to change the method param's .
This might almost be what you want:
static gint x,y ;
static void temp1(param..){
/* TODO what you needed */
values get changed here for x,y;
}
static void temp2 ( param .......){
/* accessing the x,y */
}
x and y are globally accessible, but only within the file, just like your static procedures. I think this is as close as you can get to what you want.
You need to understand these 2 things:
Scope
and
Lifetime
the scope of your static variables is only inside the function they are declared. they cannot be accessed outside.
but the lifetime of your variables is throughout your program, that is they will retain the values until the program is running.
So maybe you would like to declare your variables outside of your function. so instead of
static void temp1(param..){
static gint x,y ;
#TODO what you needed
values get changed here for x,y;
}
you can have
static gint x,y ;
static void temp1(param..){
#TODO what you needed
values get changed here for x,y;
}
The exact use case you have, i think it would not be possible without changing the second function's arguments.
static int getInnerStatic(int* _x, int* _y, int ignore);
static void temp1(param..){
static int x,y ;
////////////////
if (getInnerStatic(&x,&y,1))
return;
////////////////
#TODO what you needed
values get changed here for x,y;
}
static int getInnerStatic(int* _x, int* _y, int ignore){
static int innerInvok = 0;
static int x, y;
if (innerInvok == 1){
x = *_x;
y = *_y;
return innerInvok;//1
}
if (ignore)
return innerInvok;//0
innerInvok = 1;
temp1(/*anything as param...*/);
innerInvok = 0;
*_x = x;
*_y = y;
return innerInvok;//0
}
//get static x y :
static void temp2 ( param .......){
int getX, getY;
getInnerStatic(&getX, &getY, 0); // <- accessing the x,y
}
Here is an example of what you are trying to do:
#include <iostream>
using namespace std;
static void temp1() {
static int x,y ;
x = 5;
y = 8;
}
static void temp2 (){
cout << temp1::x << endl;
}
int main() {
temp2()
return 0;
}
Error message
error: ‘temp1’ is not a class or namespace
Note the error that occurs when you try to access x in temp1 by using the scope resolution operator ::. Here is how to solve this
#include <iostream>
using namespace std;
namespace temp {
class temp1 {
public:
static int x,y;
};
int temp1::x = 5;
int temp1::y = 7;
}
static void temp2 (){
cout << temp::temp1::x << endl;
}
int main() {
temp2();
return 0;
}
Note the namespace is not necessary, but I used it to keep related data together
You cant do that with your existing code you need to modify your code to make x and y as static instance variables so that you can access them in all the static methods.

Resources