Search Results

Search found 1848 results on 74 pages for 'printf'.

Page 8/74 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • without including #include<ctype.h>

    - by venkat
    Hi,i am written below program .... without including #include also i am able to execute the program.... where these prototype are declare? 1) include int main() { if(isalnum(';')) printf("character ; is not alphanumeric"); if(isalnum('A')) printf("character A is alphanumeric "); return 0; } 2) include int main() { printf("Lower case of A is %c \n", tolower('A')); printf("Lower case of 9 is %c \n", tolower('9')); printf("Lower case of g is %c \n", tolower('g')); printf("ASCII value of B is %d \n", toascii('B')); printf("Upper case of g is %c \n", toupper('g')); return 0; }

    Read the article

  • Manipulating matrix operations (transpose, negation, addition, and mutiplication) using functions in

    - by user292489
    I was trying to manipulate matrices in my input file using functions. My input file is: A 3 3 1 2 3 4 5 6 7 8 9 B 3 3 1 0 0 0 1 0 0 0 1 C 2 3 3 5 8 -1 -2 -3 D 3 5 0 0 0 1 0 1 0 1 0 1 0 1 0 0 1 E 1 1 10 F 3 10 1 0 2 0 3 0 4 0 5 0 0 2 3 -1 -3 -4 -3 8 3 7 0 0 0 4 6 5 8 2 -1 10 I am having trouble in implementing the functions that I declared. I assumed my program will perform those operations: transpose, negate, add, and multiply matices according to the users choice: /* once this program is compiled and executed, it will perform the basic matrix * operations: negation, transpose, addition, and multiplication. */ #include <stdio.h> #include <stdlib.h> #define MAX 10 int readmatrix(FILE *input, char martixname[6],int , mat[10][10], int i, int j); void printmatrix(char matrixname[6], int mat[10][10], int i, int j); void Negate(char matrixname[6], int mat[10][10], int i, int j); void add(char matrixname[6], int mat[10][10],int i, int k); void multiply(char matrixname[], int mat[][10], char A[], int i, int k); void transpose (char matrixname[], int mat[][10], char A[], int); void printT(int mat[][10], int); int selctoption(); char selectmatrix(); int main(int argc, char *argv[]) { char matrixtype[6]; int mat[][10]; FILE *filein; int size; int optionop; int matrixop; int option; if (argc != 2) { printf("Usage: executable input.\n"); exit(0); } filein = fopen(argv[1], "r"); if (!filein) { printf("ERROR: input file not found.\n"); exit (0); } size = readmatrix (filein, matrixtype); printmatrix(matrix[][10], size); option = selectoption(); matrixtype = selectmatrix(); //printf("You have: %5.2f ", deposit); optionop = readmatrix(option, matrix[][10], size); if (choiceop == 6) { printf("Thanks for using the matrix operation program.\n"); exit(0); } printf("Please select from the following matrix operations:\n") printf("\t1. Print matrix\n"); printf("\t2. Negate matrix\n"); printf("\t3. Transpose matrix\n"); printf("\t4. Add matrices\n"); printf("\t5. Multiply matrices\n"); printf("\t6. Quit\n"); fclose(filein); return 0; } do { printf("Please select option(1-%d):", optionop); scanf("%d", &matrixop); } while(matrixop <= 0 || matrixop > optionop); void readmatrix (FILE *in, int mat[][10], char A[], int i, int j) { int i=0,j = 0; while (fscanf(in, "%d", &mat[i][j]) != EOF) return 0; } // I would appreciate anyone's feedback.

    Read the article

  • manuplating matrix operation(transpose, negation, addition, and mutipication) using functions in c

    - by user292489
    i was trying to manuplate matrices in my input file using functions. my input file is, A 3 3 1 2 3 4 5 6 7 8 9 B 3 3 1 0 0 0 1 0 0 0 1 C 2 3 3 5 8 -1 -2 -3 D 3 5 0 0 0 1 0 1 0 1 0 1 0 1 0 0 1 E 1 1 10 F 3 10 1 0 2 0 3 0 4 0 5 0 0 2 3 -1 -3 -4 -3 8 3 7 0 0 0 4 6 5 8 2 -1 10 i am having trouble in impementing the funcitons that i declared. i assumed my program will perform those operations: transpose, negate, add, and mutiply matices according to the users choise: /* once this program is compliled and excuted, it will perform the basic matrix operations: negation, transpose,a\ ddition, and multiplication. */ #include <stdio.h> #include <stdlib.h> #define MAX 10 int readmatrix(FILE *input, char martixname[6],int , mat[10][10], int i, int j); void printmatrix(char matrixname[6], int mat[10][10], int i, int j); void Negate(char matrixname[6], int mat[10][10], int i, int j); void add(char matrixname[6], int mat[10][10],int i, int k); void multiply(char matrixname[], int mat[][10], char A[], int i, int k); void transpose (char matrixname[], int mat[][10], char A[], int); void printT(int mat[][10], int); int selctoption(); char selectmatrix(); int main(int argc, char *argv[]) { char matrixtype[6]; int mat[][10]; FILE *filein; int size; int optionop; int matrixop; int option; if (argc != 2) { printf("Usage: excutable input.\n"); exit (0); } filein = fopen(argv[1], "r"); if (!filein) { printf("ERROR: input file not found.\n"); exit (0); } size = readmatrix (filein, matrixtype); printmatrix(matrix[][10], size); option = selectoption(); matrixtype = selectmatrix(); //printf("You have: %5.2f ", deposit); optionop = readmatrix(option, matrix[][10], size); if (choiceop == 6) { printf("Thanks for using the matrix operation program.\n"); exit(0); } printf("Please select from the following matrix operations:\n") printf("\t1. Print matrix\n"); printf("\t2. Negate matrix\n"); printf("\t3. Transpose matrix\n"); printf("\t4. Add matrices\n"); printf("\t5. Multiply matrices\n"); printf("\t6. Quit\n"); fclose(filein); return 0; } do { printf("Please select option(1-%d):", optionop); scanf("%d", &matrixop); }while(matrixop <= 0 || matrixop > optionop); void readmatrix (FILE *in, int mat[][10], char A[], int i, int j) { int i=0,j = 0; while (fscanf(in, "%d", &mat[i][j]) != EOF) return 0; } // i would apprtaite anyones feedback. //thank you!

    Read the article

  • c - fork() and wait()

    - by Joe
    Hi there, I need to use the fork() and wait() functions to complete an assignment. We are modelling non-deterministic behaviour and need the program to fork() if there is more than one possible transition. In order to try and work out how fork and wait work, I have just made a simple program. I think I understand now how the calls work and would be fine if the program only branched once because the parent process could use the exit status from the single child process to determine whether the child process reached the accept state or not. As you can see from the code that follows though, I want to be able to handle situations where there must be more than one child processes. My problem is that you seem to only be able to set the status using an _exit function once. So, as in my example the exit status that the parent process tests for shows that the first child process issued 0 as it's exit status, but has no information on the second child process. I tried simply not _exit()-ing on a reject, but then that child process would carry on, and in effect there would seem to be two parent processes. Sorry for the waffle, but I would be grateful if someone could tell me how my parent process could obtain the status information on more than one child process, or I would be happy for the parent process to only notice accept status's from the child processes, but in that case I would successfully need to exit from the child processes which have a reject status. My test code is as follows: #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <sys/wait.h> int main(void) { pid_t child_pid, wpid, pid; int status = 0; int i; int a[3] = {1, 2, 1}; for(i = 1; i < 3; i++) { printf("i = %d\n", i); pid = getpid(); printf("pid after i = %d\n", pid); if((child_pid = fork()) == 0) { printf("In child process\n"); pid = getpid(); printf("pid in child process is %d\n", pid); /* Is a child process */ if(a[i] < 2) { printf("Should be accept\n"); _exit(1); } else { printf("Should be reject\n"); _exit(0); } } } if(child_pid > 0) { /* Is the parent process */ pid = getpid(); printf("parent_pid = %d\n", pid); wpid = wait(&status); if(wpid != -1) { printf("Child's exit status was %d\n", status); if(status > 0) { printf("Accept\n"); } else { printf("Complete parent process\n"); if(a[0] < 2) { printf("Accept\n"); } else { printf("Reject\n"); } } } } return 0; } Many thanks Joe

    Read the article

  • Issues writing to serial port on MAC OSX using unistd.h in c

    - by Schuyler
    I am trying to write to a bluetooth device on MAC OSX using the unistd.h Linux functions in c. I am connecting fine and writing the first few bytes with success. When I try to write other commands to it (there are bytes added to the write buffer every 15ms), I don't see any results even though the write() function returns 1 (write success). If you start a write and it doesn't finish by the time you try to start another write (since it is non-blocking), could that possibly screw up the initial write? (If so, is there any way to check if a write has completed?) That is the only thing I can think of since the writes are occurring fairly frequently and the first two are successfully sent. qwbyte() simply adds a byte to the output array and increments its length The open port function: BAMid = -1; struct termios options; struct termios originalTTYAttrs; // Open the serial port read/write, nonblocking, with no controlling terminal, and don't wait for a connection. BAMid = open(strPath, O_RDWR | O_NOCTTY | O_NONBLOCK); if (BAMid == -1) { printf("Error opening serial port %s - %s(%d).\n", strPath, strerror(errno), errno); goto error; } // Issue TIOCEXCL ioctl to prevent additional opens except by root-owned processes. if (ioctl(BAMid, TIOCEXCL) == -1) { printf("Error setting TIOCEXCL on %s - %s(%d).\n", strPath, strerror(errno), errno); goto error; } // Get the current options and save them so we can restore the default settings later. if (tcgetattr(BAMid, &originalTTYAttrs) == -1) { printf("Error getting tty attributes %s - %s(%d).\n", strPath, strerror(errno), errno); goto error; } // The serial port attributes such as timeouts and baud rate are set by modifying the termios // structure and then calling tcsetattr() to cause the changes to take effect. Note that the // changes will not become effective without the tcsetattr() call. options = originalTTYAttrs; // Set raw input (non-canonical) mode, with reads blocking until either a single character // has been received or a one second timeout expires. [should be moot since we are leaving it as nonblocking] cfmakeraw(&options); options.c_cc[VMIN] = 1; options.c_cc[VTIME] = 10; cfsetspeed(&options, B57600); // Set 57600 baud options.c_cflag |= CS8; // Use 8 bit words // Cause the new options to take effect immediately. if (tcsetattr(BAMid, TCSANOW, &options) == -1) { printf("Error setting tty attributes %s - %s(%d).\n", strPath, strerror(errno), errno); goto error; } //flush old transmissions if (tcflush(BAMid,TCIOFLUSH) == -1) { printf("Error flushing BAM serial port - %s(%d).\n", strerror(errno), errno); } oBufLength = 0; // Ask it to start if (! qwbyte(CmdStart) ) { goto error; } if (! qwbyte(CmdFull) ) { goto error; } //this transmit works txbytes(); printf("success opening port!"); return -1; // Failure path error: if (BAMid != -1) { close(BAMid); } printf("returning an error--%d",errno); return errno; } The write function (txbytes): int i, bufSize, numBytes; if(oBufLength != 0) { //if the output array isn't empty //duplicating the output array and its size so it can //be overwritten while this write is occuring printf("about to transmit: "); for(i = 0; i < oBufLength; i++) { printf(" %u",oBuf[i]); tempBuf[i] = oBuf[i]; } printf("\n"); bufSize = oBufLength; oBufLength = 0; numBytes = write(BAMid, &tempBuf, bufSize); printf("bytes written = %d\n",numBytes); if (numBytes == -1) { printf("Error writing to port - %s(%d).\n", strerror(errno), errno); } return (numBytes 0); } else { return 0; }

    Read the article

  • Mallocing an unsigned char array to store ints

    - by Max Desmond
    I keep getting a segmentation fault when i test the following code. I am currently unable to find an answer after having searched the web. a = (byte *)malloc(sizeof(byte) * x ) ; for( i = 0 ; i < x-1 ; i++ ) { scanf("%d", &y ) ; a[i] = y ; } Both y and x are initialized. X is the size of the array determined by the user. The segmentation fault is on the second to last integer to be added, i found this by adding printf("roar") ; before setting a[i] to y and entering one number at a time. Byte is a typedef of an unsigned char. Note: I've also tried using a[i] = (byte)y ; A is ininitalized as follows byte *a ; If you need to view the entire code it is this: #include <stdio.h> #include <stdlib.h> #include "sort.h" int p_cmp_f () ; int main( int argc, char *argv[] ) { int x, y, i, choice ; byte *a ; while( choice !=2 ) { printf( "Would you like to sort integers?\n1. Yes\n2. No\n" ) ; scanf("%d", &choice ) ; switch(choice) { case 1: printf( "Enter the length of the array: " ) ; scanf( "%d", &x ) ; a = (byte *)malloc(sizeof( byte ) * x ) ; printf( "Enter %d integers to add to the array: ", x ) ; for( i = 0 ; i < x -1 ; i++ ) { scanf( "%d", &y ) ; a[i] = y ; } switch( choice ) { case 1: bubble_sort( a, x, sizeof(int), p_cmp_f ) ; for( i = 0 ; i < x ; i++ ) printf( "%d", a[i] ; break ; case 2: selection_sort( a, x, sizeof(int), p_cmp_f ) ; for( i = 0 ; i < x; i++ ) printf( "%d", a[i] ; break ; case 3: insertion_sort( a, x, sizeof(int), p_cmp_f ) ; for( i = 0 ; i < x ; i++ ) printf( "%d", a[i] ; break ; case 4: merge_sort( a, x, sizeof(int), p_cmp_f ) ; for( i = 0 ; i < x ; i++ ) printf( "%d", a[i] ; break ; case 5: quick_sort( a, x, sizeof(int), p_cmp_f ) ; for( i = 0 ; i < x ; i++ ) printf( "%d", a[i] ; break ; default: printf("Enter either 1,2,3,4, or 5" ) ; break ; } case 2: printf( "Thank you for using this program\n" ) ; return 0 ; break ; default: printf( "Enter either 1 or 2: " ) ; break ; } } free(a) ; return 0 ; } int p_cmp_f( byte *element1, byte *element2 ) { return *((int *)element1) - *((int *)element2) ; }

    Read the article

  • Vertex buffer acting strange? [on hold]

    - by Ryan Capote
    I'm having a strange problem, and I don't know what could be causing it. My current code is identical to how I've done this before. I'm trying to render a rectangle using VBO and orthographic projection.   My results:     What I expect: 3x3 rectangle in the top left corner   #include <stdio.h> #include <GL\glew.h> #include <GLFW\glfw3.h> #include "lodepng.h"   static const int FALSE = 0; static const int TRUE = 1;   static const char* VERT_SHADER =     "#version 330\n"       "layout(location=0) in vec4 VertexPosition; "     "layout(location=1) in vec2 UV;"     "uniform mat4 uProjectionMatrix;"     /*"out vec2 TexCoords;"*/       "void main(void) {"     "    gl_Position = uProjectionMatrix*VertexPosition;"     /*"    TexCoords = UV;"*/     "}";   static const char* FRAG_SHADER =     "#version 330\n"       /*"uniform sampler2D uDiffuseTexture;"     "uniform vec4 uColor;"     "in vec2 TexCoords;"*/     "out vec4 FragColor;"       "void main(void) {"    /* "    vec4 texel = texture2D(uDiffuseTexture, TexCoords);"     "    if(texel.a <= 0) {"     "         discard;"     "    }"     "    FragColor = texel;"*/     "    FragColor = vec4(1.f);"     "}";   static int g_running; static GLFWwindow *gl_window; static float gl_projectionMatrix[16];   /*     Structures */ typedef struct _Vertex {     float x, y, z, w;     float u, v; } Vertex;   typedef struct _Position {     float x, y; } Position;   typedef struct _Bitmap {     unsigned char *pixels;     unsigned int width, height; } Bitmap;   typedef struct _Texture {     GLuint id;     unsigned int width, height; } Texture;   typedef struct _VertexBuffer {     GLuint bufferObj, vertexArray; } VertexBuffer;   typedef struct _ShaderProgram {     GLuint vertexShader, fragmentShader, program; } ShaderProgram;   /*   http://en.wikipedia.org/wiki/Orthographic_projection */ void createOrthoProjection(float *projection, float width, float height, float far, float near)  {       const float left = 0;     const float right = width;     const float top = 0;     const float bottom = height;          projection[0] = 2.f / (right - left);     projection[1] = 0.f;     projection[2] = 0.f;     projection[3] = -(right+left) / (right-left);     projection[4] = 0.f;     projection[5] = 2.f / (top - bottom);     projection[6] = 0.f;     projection[7] = -(top + bottom) / (top - bottom);     projection[8] = 0.f;     projection[9] = 0.f;     projection[10] = -2.f / (far-near);     projection[11] = (far+near)/(far-near);     projection[12] = 0.f;     projection[13] = 0.f;     projection[14] = 0.f;     projection[15] = 1.f; }   /*     Textures */ void loadBitmap(const char *filename, Bitmap *bitmap, int *success) {     int error = lodepng_decode32_file(&bitmap->pixels, &bitmap->width, &bitmap->height, filename);       if (error != 0) {         printf("Failed to load bitmap. ");         printf(lodepng_error_text(error));         success = FALSE;         return;     } }   void destroyBitmap(Bitmap *bitmap) {     free(bitmap->pixels); }   void createTexture(Texture *texture, const Bitmap *bitmap) {     texture->id = 0;     glGenTextures(1, &texture->id);     glBindTexture(GL_TEXTURE_2D, texture);       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);       glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bitmap->width, bitmap->height, 0,              GL_RGBA, GL_UNSIGNED_BYTE, bitmap->pixels);       glBindTexture(GL_TEXTURE_2D, 0); }   void destroyTexture(Texture *texture) {     glDeleteTextures(1, &texture->id);     texture->id = 0; }   /*     Vertex Buffer */ void createVertexBuffer(VertexBuffer *vertexBuffer, Vertex *vertices) {     glGenBuffers(1, &vertexBuffer->bufferObj);     glGenVertexArrays(1, &vertexBuffer->vertexArray);     glBindVertexArray(vertexBuffer->vertexArray);       glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer->bufferObj);     glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * 6, (const GLvoid*)vertices, GL_STATIC_DRAW);       const unsigned int uvOffset = sizeof(float) * 4;       glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);     glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)uvOffset);       glEnableVertexAttribArray(0);     glEnableVertexAttribArray(1);       glBindBuffer(GL_ARRAY_BUFFER, 0);     glBindVertexArray(0); }   void destroyVertexBuffer(VertexBuffer *vertexBuffer) {     glDeleteBuffers(1, &vertexBuffer->bufferObj);     glDeleteVertexArrays(1, &vertexBuffer->vertexArray); }   void bindVertexBuffer(VertexBuffer *vertexBuffer) {     glBindVertexArray(vertexBuffer->vertexArray);     glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer->bufferObj); }   void drawVertexBufferMode(GLenum mode) {     glDrawArrays(mode, 0, 6); }   void drawVertexBuffer() {     drawVertexBufferMode(GL_TRIANGLES); }   void unbindVertexBuffer() {     glBindVertexArray(0);     glBindBuffer(GL_ARRAY_BUFFER, 0); }   /*     Shaders */ void compileShader(ShaderProgram *shaderProgram, const char *vertexSrc, const char *fragSrc) {     GLenum err;     shaderProgram->vertexShader = glCreateShader(GL_VERTEX_SHADER);     shaderProgram->fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);       if (shaderProgram->vertexShader == 0) {         printf("Failed to create vertex shader.");         return;     }       if (shaderProgram->fragmentShader == 0) {         printf("Failed to create fragment shader.");         return;     }       glShaderSource(shaderProgram->vertexShader, 1, &vertexSrc, NULL);     glCompileShader(shaderProgram->vertexShader);     glGetShaderiv(shaderProgram->vertexShader, GL_COMPILE_STATUS, &err);       if (err != GL_TRUE) {         printf("Failed to compile vertex shader.");         return;     }       glShaderSource(shaderProgram->fragmentShader, 1, &fragSrc, NULL);     glCompileShader(shaderProgram->fragmentShader);     glGetShaderiv(shaderProgram->fragmentShader, GL_COMPILE_STATUS, &err);       if (err != GL_TRUE) {         printf("Failed to compile fragment shader.");         return;     }       shaderProgram->program = glCreateProgram();     glAttachShader(shaderProgram->program, shaderProgram->vertexShader);     glAttachShader(shaderProgram->program, shaderProgram->fragmentShader);     glLinkProgram(shaderProgram->program);          glGetProgramiv(shaderProgram->program, GL_LINK_STATUS, &err);       if (err != GL_TRUE) {         printf("Failed to link shader.");         return;     } }   void destroyShader(ShaderProgram *shaderProgram) {     glDetachShader(shaderProgram->program, shaderProgram->vertexShader);     glDetachShader(shaderProgram->program, shaderProgram->fragmentShader);       glDeleteShader(shaderProgram->vertexShader);     glDeleteShader(shaderProgram->fragmentShader);       glDeleteProgram(shaderProgram->program); }   GLuint getUniformLocation(const char *name, ShaderProgram *program) {     GLuint result = 0;     result = glGetUniformLocation(program->program, name);       return result; }   void setUniformMatrix(float *matrix, const char *name, ShaderProgram *program) {     GLuint loc = getUniformLocation(name, program);       if (loc == -1) {         printf("Failed to get uniform location in setUniformMatrix.\n");         return;     }       glUniformMatrix4fv(loc, 1, GL_FALSE, matrix); }   /*     General functions */ static int isRunning() {     return g_running && !glfwWindowShouldClose(gl_window); }   static void initializeGLFW(GLFWwindow **window, int width, int height, int *success) {     if (!glfwInit()) {         printf("Failed it inialize GLFW.");         *success = FALSE;        return;     }          glfwWindowHint(GLFW_RESIZABLE, 0);     *window = glfwCreateWindow(width, height, "Alignments", NULL, NULL);          if (!*window) {         printf("Failed to create window.");         glfwTerminate();         *success = FALSE;         return;     }          glfwMakeContextCurrent(*window);       GLenum glewErr = glewInit();     if (glewErr != GLEW_OK) {         printf("Failed to initialize GLEW.");         printf(glewGetErrorString(glewErr));         *success = FALSE;         return;     }       glClearColor(0.f, 0.f, 0.f, 1.f);     glViewport(0, 0, width, height);     *success = TRUE; }   int main(int argc, char **argv) {          int err = FALSE;     initializeGLFW(&gl_window, 480, 320, &err);     glDisable(GL_DEPTH_TEST);     if (err == FALSE) {         return 1;     }          createOrthoProjection(gl_projectionMatrix, 480.f, 320.f, 0.f, 1.f);          g_running = TRUE;          ShaderProgram shader;     compileShader(&shader, VERT_SHADER, FRAG_SHADER);     glUseProgram(shader.program);     setUniformMatrix(&gl_projectionMatrix, "uProjectionMatrix", &shader);       Vertex rectangle[6];     VertexBuffer vbo;     rectangle[0] = (Vertex){0.f, 0.f, 0.f, 1.f, 0.f, 0.f}; // Top left     rectangle[1] = (Vertex){3.f, 0.f, 0.f, 1.f, 1.f, 0.f}; // Top right     rectangle[2] = (Vertex){0.f, 3.f, 0.f, 1.f, 0.f, 1.f}; // Bottom left     rectangle[3] = (Vertex){3.f, 0.f, 0.f, 1.f, 1.f, 0.f}; // Top left     rectangle[4] = (Vertex){0.f, 3.f, 0.f, 1.f, 0.f, 1.f}; // Bottom left     rectangle[5] = (Vertex){3.f, 3.f, 0.f, 1.f, 1.f, 1.f}; // Bottom right       createVertexBuffer(&vbo, &rectangle);            bindVertexBuffer(&vbo);          while (isRunning()) {         glClear(GL_COLOR_BUFFER_BIT);         glfwPollEvents();                    drawVertexBuffer();                    glfwSwapBuffers(gl_window);     }          unbindVertexBuffer(&vbo);       glUseProgram(0);     destroyShader(&shader);     destroyVertexBuffer(&vbo);     glfwTerminate();     return 0; }

    Read the article

  • C Programming matrix

    - by Bilal Khan
    In this program the user enters the # of columns of the matrix and then the entries of the matrix. So, for example, if the user enters 2 for column # and 1 2 3 4 for entries then the program develops a 2 by 2 matrix with 1 2 3 4 as entries. My program works perfectly in such a case. However, if the user for example had only entered 1 2 3 then my program makes a matrix with garbage values. I would like the program in such a case to exit the program. It is a simple question, but it has me baffled. #include<stdio.h> #include<stdlib.h> int main() { int m,x, n, c = 0, d,k, matrix[10][10], transpose[10][10], product[10][10]; printf("Enter the number of columns of matrix "); scanf("%d",&m); if(m<=0){ printf("You entered a invalid value."); exit(0); } else{ printf("Enter the elements of matrix \n"); for( c = 0 ; c < 10 ; c++ ) { for( d = 0 ; d < m ; d++ ) { scanf("%d",&matrix[c][d]); if (matrix[c][d] == 99) // 'x' is character variable I declared to use as a break break; // c = c+1; } if (matrix[c][d] == 99) break; } } printf("\nHere is your matrix:\n"); int i; for(i=0;i<c;i++) { for(d=0;d<m;d++) { printf("%3d ",matrix[i][d]); } printf("\n"); }

    Read the article

  • Pointers inside a structure [on hold]

    - by user3402552
    I have the next program: #include<stdio.h> #include<stdlib.h> struct a { char *ch; char *str; }; int main() { struct a s1; char ptr[100]; int m, n; printf("\n Enter a string : "); gets(ptr); m = strlen(ptr); s1.ch = (char *)malloc(strlen(ptr) * sizeof(char)); if(s1.ch) { strcpy(s1.ch, ptr); } else { printf("\n Alocation failed!\n"); } printf("\n %s\n\n", s1.ch); while(*s1.ch) { printf(" %c", *(s1.ch)); s1.ch++; } printf("\n\n"); s1.ch = s1.ch - m; printf("\n\n\n %s \n\n", s1.ch); } Is this ok this program in this way ? I mean the pointers should not be initialized ? And if it is not ok, why compile it without errors?

    Read the article

  • C socket programming: calling recv() changes my socket file descriptor?

    - by fourier
    Hey all, I have this strange problem with recv(). I'm programming client/server where client send() a message (a structure to be exact) and server recv() it. I am also working with multiple sockets and select(). while(1) { readset = info->read_set; info->copy_set = info->read_set; timeout.tv_sec = 1; timeout.tv_usec = 0; // 0.5 seconds ready = select(info->max_fd+1, &readset, NULL, NULL, &timeout); if (ready == -1) { printf("S: ERROR: select(): %s\nEXITING...", strerror(errno)); exit(1); } else if (ready == 0) { continue; } else { printf("S: oh finally you have contacted me!\n"); for(i = 0; i < (info->max_fd+1); i++) { if(FD_ISSET(i, &readset)) //this is where problem begins { printf("S: %i is set\n", i); printf("S: we talking about socket %i son\n", i); // i = 4 num_bytes = recv(i, &msg, MAX_MSG_BYTE, 0); printf("S: number of bytes recieved in socket %i is %i\n", i, num_bytes); // prints out i = 0 what?? if (num_bytes == 0) { printf("S: socket has been closed\n"); break; } else if (num_bytes == -1) { printf("S: ERROR recv: %d %s \n", i, strerror(errno)); continue; } else { handle_request(arg, &msg); printf("S: msg says %s\n", msg->_payload); } } // if (FD_ISSET(i, &readset) else printf("S: %i is not set\n", i); } // for (i = 0; i < maxfd+1; i++) to check sockets for msg } // if (ready == -1) info->read_set = info->copy_set; printf("S: copied\n"); } the problem I have is that in read_set, 0~3 aren't set and 4 is. That is fine. But when i call recv(), i suddently becomes 0. Why is that? It doesn't make sense to me why recv() would take an socket file descriptor number and modify to another number. Is that normal? Am I missing something? S: 0 is not set S: 1 is not set S: 2 is not set S: 3 is not set S: 4 is set S: we talking about socket 4 son S: i is strangely or unstrangely 0 S: number of bytes recieved in socket 0 is 40 That's what it prints out.

    Read the article

  • Infinite loop when using fscanf

    - by user1409641
    I wrote this simple program in C, because I'm studying FILES right now at University. I take a txt file with a list of the results of the last race so my program will show the data formatted as I want. Here's my code: /* Esercizio file Motogp */ #include <stdio.h> #define SIZE 20 int main () { int pos, punt, num; float kmh; char nome[SIZE+1], cognome[SIZE+1], moto[SIZE+1]; char naz[SIZE+1], nome_file[SIZE+1]; FILE *fp; printf ("Inserisci il nome del file da aprire: "); gets (nome_file); fp = fopen (nome_file, "r"); if (fopen == NULL) printf ("Errore nell' apertura del file %s\n", nome_file); else { while (fscanf (fp, "%d %d %d %s %s %s %s %.2f", &pos, &punt, &num, nome, cognome, naz, moto, &kmh) != EOF ) { printf ("Posizione di arrivo: %d\n", pos); printf ("Punteggio: %d\n", punt); printf ("Numero pilota: %d\n", num); printf ("Nome pilota: %s\n", nome); printf ("Cognome pilota: %s\n", cognome); printf ("Nazione: %s\n", naz); printf ("Moto: %s\n", moto); printf ("Media Kmh: %d\n\n", kmh); } } fclose(fp); return 0; } and there's my txt file: 1 25 99 Jorge LORENZO SPA Yamaha 164.4 2 20 26 Dani PEDROSA SPA Honda 164.1 3 16 4 Andrea DOVIZIOSO ITA Yamaha 163.8 4 13 1 Casey STONER AUS Honda 163.8 5 11 35 Cal CRUTCHLOW GBR Yamaha 163.6 6 10 19 Alvaro BAUTISTA SPA Honda 163.5 7 9 46 Valentino ROSSI ITA Ducati 163.3 8 8 6 Stefan BRADL GER Honda 162.9 9 7 69 Nicky HAYDEN USA Ducati 162.5 10 6 11 Ben SPIES USA Yamaha 162.3 11 5 8 Hector BARBERA SPA Ducati 162.1 12 4 17 Karel ABRAHAM CZE Ducati 160.9 13 3 41 Aleix ESPARGARO SPA ART 160.2 14 2 51 Michele PIRRO ITA FTR 160.1 15 1 14 Randy DE PUNIET FRA ART 160.0 16 0 77 James ELLISON GBR ART 159.9 17 0 54 Mattia PASINI ITA ART 159.4 18 0 68 Yonny HERNANDEZ COL BQR 159.4 19 0 9 Danilo PETRUCCI ITA Ioda 158.2 20 0 22 Ivan SILVA SPA BQR 158.2 When I run my program, it return me an infinite loop of the first one. Why? Is there another function to read those data?

    Read the article

  • Stack Overflow Exploit in C

    - by Fernando Gonzalez
    Hey there guys, the question is actually about stack overflows in C. I have an assigment that I can not get done for the life of me, i've looked at everything in the gdb and I just cant figure it. The question is the following: int i,n; void confused() { printf("who called me"); exit(0); } void shell_call(char *c) { printf(" ***Now calling \"%s\" shell command *** \n",c); system(c); exit(0); } void victim_func() { int a[4]; printf("[8]:%x\n", &a[8]); printf("Enter n: "); scanf("%d",&n); printf("Enter %d HEX Values \n",n); for(i=0;i<n;i++) scanf("%x",&a[i]); printf("Done reading junk numbers\n"); } int main() { printf("ls=736c --- ps = 7370 --- cal = 6c6163\n"); printf("location of confused %x \n", confused); printf("location of shell_call %x \n", shell_call); victim_func(); printf("Done, thank you\n"); } Ok, so I managed to get the first question correctly, which is to arbitrarily call one of the two functions not explicitly called in the main path. By the way, this has to be done while running the program without any modifications. I did this by running the program, setting N to 7, which gets me to the Function Pointer of the victim_func frame, I write a[7] with the memory address of confused or shell_call, and it works. (I have a 64 bit machine, thats why I have to get it to 7, since the EBI pointer is 2 ints wide, instead of 1) My question is the following, how could I control which argument gets passed to the shell_code funcion? ie. how do i write a string to char* c. The whole point is executing unix commands like "ps" etc, by running only the program. I figured writing the EBI pointer with the hex representation of "ps" and setting the arg list of shell_call to that, but that didn't work. I also tried inputing argsv arguments and setting the arg list of shell_call to the arg_list of main, but didnt work either. I think the second version should work, but i believe im not setting the arg list of the new stack frame correctly ( I did it by writing a[8] to 0, since its the first part of the functin pointer, and writing a[9]=736c and a[10]=0000, but its probably not right since those are the parameters of victim_func. So how do i access the parameters of shell_call?

    Read the article

  • Inserting Records in Ascending Order function- C homework assignment

    - by Aaron McRuer
    Good day, Stack Overflow. I have a homework assignment that I'm working on this weekend that I'm having a bit of a problem with. We have a struct "Record" (which contains information about cars for a dealership) that gets placed in a particular spot in a linked list according to 1) its make and 2) according to its model year. This is done when initially building the list, when a "int insertRecordInAscendingOrder" function is called in Main. In "insertRecordInAscendingOrder", a third function, "createRecord" is called, where the linked list is created. The function then goes to the function "compareCars" to determine what elements get put where. Depending on the value returned by this function, insertRecordInAscendingOrder then places the record where it belongs. The list is then printed out. There's more to the assignment, but I'll cross that bridge when I come to it. Ideally, and for the assignment to be considered correct, the linked list must be ordered as: Chevrolet 2012 25 Chevrolet 2013 10 Ford 2010 5 Ford 2011 3 Ford 2012 15 Honda 2011 9 Honda 2012 3 Honda 2013 12 Toyota 2009 2 Toyota 2011 7 Toyota 2013 20 from the a text file that has the data ordered the following way: Ford 2012 15 Ford 2011 3 Ford 2010 5 Toyota 2011 7 Toyota 2012 20 Toyota 2009 2 Honda 2011 9 Honda 2012 3 Honda 2013 12 Chevrolet 2013 10 Chevrolet 2012 25 Notice that the alphabetical order of the "make" field takes precedence, then, the model year is arranged from oldest to newest. However, the program produces this as the final list: Chevrolet 2012 25 Chevrolet 2013 10 Honda 2011 9 Honda 2012 3 Honda 2013 12 Toyota 2009 2 Toyota 2011 7 Toyota 2012 20 Ford 2010 5 Ford 2011 3 Ford 2012 15 I sat down with a grad student and tried to work out all of this yesterday, but we just couldn't figure out why it was kicking the Ford nodes down to the end of the list. Here's the code. As you'll notice, I included a printList call at each instance of the insertion of a node. This way, you can see just what is happening when the nodes are being put in "order". It is in ANSI C99. All function calls must be made as they are specified, so unfortunately, there's no real way of getting around this problem by creating a more efficient algorithm. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LINE 50 #define MAX_MAKE 20 typedef struct record { char *make; int year; int stock; struct record *next; } Record; int compareCars(Record *car1, Record *car2); void printList(Record *head); Record* createRecord(char *make, int year, int stock); int insertRecordInAscendingOrder(Record **head, char *make, int year, int stock); int main(int argc, char **argv) { FILE *inFile = NULL; char line[MAX_LINE + 1]; char *make, *yearStr, *stockStr; int year, stock, len; Record* headRecord = NULL; /*Input and file diagnostics*/ if (argc!=2) { printf ("Filename not provided.\n"); return 1; } if((inFile=fopen(argv[1], "r"))==NULL) { printf("Can't open the file\n"); return 2; } /*obtain values for linked list*/ while (fgets(line, MAX_LINE, inFile)) { make = strtok(line, " "); yearStr = strtok(NULL, " "); stockStr = strtok(NULL, " "); year = atoi(yearStr); stock = atoi(stockStr); insertRecordInAscendingOrder(&headRecord,make, year, stock); } printf("The original list in ascending order: \n"); printList(headRecord); } /*use strcmp to compare two makes*/ int compareCars(Record *car1, Record *car2) { int compStrResult; compStrResult = strcmp(car1->make, car2->make); int compYearResult = 0; if(car1->year > car2->year) { compYearResult = 1; } else if(car1->year == car2->year) { compYearResult = 0; } else { compYearResult = -1; } if(compStrResult == 0 ) { if(compYearResult == 1) { return 1; } else if(compYearResult == -1) { return -1; } else { return compStrResult; } } else if(compStrResult == 1) { return 1; } else { return -1; } } int insertRecordInAscendingOrder(Record **head, char *make, int year, int stock) { Record *previous = *head; Record *newRecord = createRecord(make, year, stock); Record *current = *head; int compResult; if(*head == NULL) { *head = newRecord; printf("Head is null, list was empty\n"); printList(*head); return 1; } else if ( compareCars(newRecord, *head)==-1) { *head = newRecord; (*head)->next = current; printf("New record was less than the head, replacing\n"); printList(*head); return 1; } else { printf("standard case, searching and inserting\n"); previous = *head; while ( current != NULL &&(compareCars(newRecord, current)==1)) { printList(*head); previous = current; current = current->next; } printList(*head); previous->next = newRecord; previous->next->next = current; } return 1; } /*creates records from info passed in from main via insertRecordInAscendingOrder.*/ Record* createRecord(char *make, int year, int stock) { printf("CreateRecord\n"); Record *theRecord; int len; if(!make) { return NULL; } theRecord = malloc(sizeof(Record)); if(!theRecord) { printf("Unable to allocate memory for the structure.\n"); return NULL; } theRecord->year = year; theRecord->stock = stock; len = strlen(make); theRecord->make = malloc(len + 1); strncpy(theRecord->make, make, len); theRecord->make[len] = '\0'; theRecord->next=NULL; return theRecord; } /*prints list. lists print.*/ void printList(Record *head) { int i; int j = 50; Record *aRecord; aRecord = head; for(i = 0; i < j; i++) { printf("-"); } printf("\n"); printf("%20s%20s%10s\n", "Make", "Year", "Stock"); for(i = 0; i < j; i++) { printf("-"); } printf("\n"); while(aRecord != NULL) { printf("%20s%20d%10d\n", aRecord->make, aRecord->year, aRecord->stock); aRecord = aRecord->next; } printf("\n"); } The text file you'll need for a command line argument can be saved under any name you like; here are the contents you'll need: Ford 2012 15 Ford 2011 3 Ford 2010 5 Toyota 2011 7 Toyota 2012 20 Toyota 2009 2 Honda 2011 9 Honda 2012 3 Honda 2013 12 Chevrolet 2013 10 Chevrolet 2012 25 Thanks in advance for your help. I shall continue to plow away at it myself.

    Read the article

  • C strange array behaviour

    - by LukeN
    After learning that both strncmp is not what it seems to be and strlcpy not being available on my operating system (Linux), I figured I could try and write it myself. I found a quote from Ulrich Drepper, the libc maintainer, who posted an alternative to strlcpy using mempcpy. I don't have mempcpy either, but it's behaviour was easy to replicate. First of, this is the testcase I have #include <stdio.h> #include <string.h> #define BSIZE 10 void insp(const char* s, int n) { int i; for (i = 0; i < n; i++) printf("%c ", s[i]); printf("\n"); for (i = 0; i < n; i++) printf("%02X ", s[i]); printf("\n"); return; } int copy_string(char *dest, const char *src, int n) { int r = strlen(memcpy(dest, src, n-1)); dest[r] = 0; return r; } int main() { char b[BSIZE]; memset(b, 0, BSIZE); printf("Buffer size is %d", BSIZE); insp(b, BSIZE); printf("\nFirst copy:\n"); copy_string(b, "First", BSIZE); insp(b, BSIZE); printf("b = '%s'\n", b); printf("\nSecond copy:\n"); copy_string(b, "Second", BSIZE); insp(b, BSIZE); printf("b = '%s'\n", b); return 0; } And this is its result: Buffer size is 10 00 00 00 00 00 00 00 00 00 00 First copy: F i r s t b = 46 69 72 73 74 00 62 20 3D 00 b = 'First' Second copy: S e c o n d 53 65 63 6F 6E 64 00 00 01 00 b = 'Second' You can see in the internal representation (the lines insp() created) that there's some noise mixed in, like the printf() format string in the inspection after the first copy, and a foreign 0x01 in the second copy. The strings are copied intact and it correctly handles too long source strings (let's ignore the possible issue with passing 0 as length to copy_string for now, I'll fix that later). But why are there foreign array contents (from the format string) inside my destination? It's as if the destination was actually RESIZED to match the new length.

    Read the article

  • Ethernet Communication Error

    - by SivaKumar
    Hi, I wrote a program to query the status of the Ethernet printer for that i created a TCP Stream Socket and i send the query command to the printer.In case of Error less condition it returns No error status but in error case its getting hang at recv command.Even i used Non blocking now the recv command returns nothing and error set as Resource temporarily unavailable. code: #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <errno.h> #include <stdlib.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <signal.h> #include <termios.h> #include <poll.h> #include <netinet/tcp.h> #include <stdarg.h> int main() { int ConnectSocket,ConnectSocket1,select_err,err,nRet,nBytesRead; struct timeval waitTime = {10,30}; fd_set socket_set; unsigned char * dataBuf = NULL; unsigned char tempVar, tempVar1, tempVar2, tempVar3; char reset[] = "\033E 2\r"; char print[] = "\033A 1\r"; char buf[1024]={0}; ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); printf("The Socket ID is %d\n",ConnectSocket); if (ConnectSocket < 0) { perror("socket()"); return 0; } struct sockaddr_in clientService; clientService.sin_family = AF_INET; clientService.sin_addr.s_addr = inet_addr("192.168.0.129"); //Printer IP clientService.sin_port = htons( 9100); // Printer Port if ( connect( ConnectSocket, (struct sockaddr*) &clientService, sizeof(clientService) ) == -1) { perror("connect()"); close(ConnectSocket); return -1; } /* if((nRet = ioctl(ConnectSocket , FIONREAD, &nBytesRead) == -1)) { perror("ioctl()"); } perror("ioctl()"); */ FD_ZERO(&socket_set); FD_SET(ConnectSocket, &socket_set); do { errno=0; select_err = select(ConnectSocket+1, NULL, &socket_set, NULL, &waitTime); }while(errno==EINPROGRESS); if (-1 == select_err || 0 == select_err) { int optVal = 0; int optLen = sizeof(optVal); if(select_err == -1) { perror("select() write-side"); } else { //Timeout errno=0; err = getsockopt(ConnectSocket, SOL_SOCKET, SO_ERROR, (char*)&optVal, &optLen); printf("the return of the getsockopt is %d\n",err); printf("the opt val is %s\n",(char*)optVal); perror("getsockopt()"); if(err == -1) { perror("getsockopt() write-side"); } } printf("Select Failed during write - ConnectSocket: %d\n", ConnectSocket); //close(ConnectSocket); return -1; } err = send(ConnectSocket,print,sizeof(print)-1, 0); printf("\n No of Bytes Send is %d\n",err); if(err == -1 || err ==0) { perror("send()"); //close(ConnectSocket); return -1; } FD_ZERO(&socket_set); FD_SET(ConnectSocket, &socket_set); do { errno=0; select_err = select(ConnectSocket+1, NULL, &socket_set, NULL, &waitTime); }while(errno==EINPROGRESS); if (-1 == select_err || 0 == select_err) { printf("Select Failed during write - ConnectSocket: %d\n", ConnectSocket); return -1; } err = send(ConnectSocket,reset,sizeof(reset)-1, 0); printf("\n No of Bytes Send is %d\n",err); if(err == -1 || err ==0) { perror("send()"); //close(ConnectSocket); return -1; } FD_ZERO(&socket_set); FD_SET(ConnectSocket, &socket_set); printf("i am in reading \n"); select_err = select(ConnectSocket+1, &socket_set, NULL, NULL, &waitTime); printf("the retun of the read side select is %d \n",select_err); perror("select()"); if (-1 == select_err|| 0 == select_err) { printf("Read timeout; ConnectSocket: %d\n", ConnectSocket); close(ConnectSocket); perror("close()"); return -1; } printf("Before Recv\n"); nBytesRead = recv(ConnectSocket , buf, 1024, 0); printf("No of Bytes read is %d\n",nBytesRead); printf("%s\n",buf); if(nBytesRead == -1) { perror("recv()"); close(ConnectSocket); perror("clode()"); return -1; } close(ConnectSocket); return 1; }

    Read the article

  • How to write a C program using the fork() system call that generates the Fibonacci sequence in the

    - by Ellen
    The problem I am having is that when say for instance the user enters 7, then the display shows: 0 11 2 3 5 8 13 21 child ends. I cannot seem to figure out how to fix the 11 and why is it displaying that many numbers in the sequence! Can anyone help? The number of the sequence will be provided in the command line. For example, if 5 is provided, the first five numbers in the Fibonacci sequence will be output by the child process. Because the parent and child processes have their own copies of the data, it will be necessary for the child to output the sequence. Have the parent invoke the wait() call to wait for the child process to complete before exiting the program. Perform necessary error checking to ensure that a non-negative number is passed on the command line. #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main() { int a=0, b=1, n=a+b,i,ii; pid_t pid; printf("Enter the number of a Fibonacci Sequence:\n"); scanf("%d", &ii); if (ii < 0) printf("Please enter a non-negative integer!\n"); else { pid = fork(); if (pid == 0) { printf("Child is producing the Fibonacci Sequence...\n"); printf("%d %d",a,b); for (i=0;i<ii;i++) { n=a+b; printf("%d ", n); a=b; b=n; } printf("Child ends\n"); } else { printf("Parent is waiting for child to complete...\n"); wait(NULL); printf("Parent ends\n"); } } return 0; }

    Read the article

  • VERY simple C program won't compile with VC 64

    - by Paperflyer
    Here is a very simple C program: #include <stdio.h> int main (int argc, char *argv[]) { printf("sizeof(short) = %d\n",(int)sizeof(short)); printf("sizeof(int) = %d\n",(int)sizeof(int)); printf("sizeof(long) = %d\n",(int)sizeof(long)); printf("sizeof(long long) = %d\n",(int)sizeof(long long)); printf("sizeof(float) = %d\n",(int)sizeof(float)); printf("sizeof(double) = %d\n",(int)sizeof(double)); return 0; } While it compiles fine on Win32 (command line: cl main.c), it does not using the Win64 compiler ("c:\Program Files(x86)\Microsoft Visual Studio 9.0\VC\bin\amd64\cl.exe" main.c). Specifically, it sais "error LNK2019: unresolved external symbol printf referenced in function main". As far as I understand this, it can not link to printf, right? Obviously, I have Microsoft Visual C++ Compiler 2008 (Standard enu) x86 and x64 installed and am using the 64-bit flavor of Windows (7). What is the problem here?

    Read the article

  • Segmentation fault on certain inputs and not others

    - by Brandon Schwandt
    Heres a function I wrote that has some debugging elements in it already. When i enter either a "y" or a "Y" as the input I get a segmentation fault during runtime. When I enter any other value the code runs. The seg fault kicks out after it scans and gives me the response but before the "scan worked" line is output. DOn't know why it would act like this only on these values. If anyone needs the function call I have that as well. query_user(char *response [10]) { printf("response after query call before clear=%s\n",response); strcpy(response,""); printf("response after clearing before scan=%s\n",response); printf("Enter another person into the line? y or n\n"); scanf("%s", response); printf("response after scan=%s\n",response); printf("scan worked"); } main() { char response [10]; strcpy(response,"y"); printf("response=%s\n",response); printf("When finished with program type \"done\" to exit\n"); while (strcmp(response,"done") != 0) { printf("response after while loop and before query call=%s\n",response); query_user(&response); } } output on error: response after query call before clear=y response after clearing before scan= Enter another person into the line? y or n y response after scan=y Segmentation Fault (core dumped) output on non-error: response after query call before clear=y response after clearing before scan= Enter another person into the line? y or n n response after scan=n scan worked Cycle number 0 (program continues to run outside this function)

    Read the article

  • segmentation fault while using format string to scan input

    - by Aman Deep Gautam
    consider the code and its result: while ((row = mysql_fetch_row (table_info)) != NULL) { answer='\0'; printf ( "%s: ", row[0] ); scanf ( "%c", &answer ); getchar(); if ( answer == 'y') { printf ( "*****\n" ); table_name[index] = malloc ( strlen(row[0]) + 1 ); printf ( "*****\n" ); memcpy ( &table_name[index], &row[0], strlen(row[0]) + 1 ); } printf ( "finally inserted: %s \n", table_name[index]); } The result on execution: 1_time_access: y ***** ***** finally inserted: 1_time_access 2_time_access: y ***** ***** finally inserted: 2_time_access 39_time_access: y ***** ***** finally inserted: 39_time_access Explanation of result: row[0] has value 1_time_access, 2_time_access, 39_time_access. Now Consider a better way of doing it which is using a format string to escape the \n. I run the following code but it gives segentation fault, I cannot understand why. Code: while ((row = mysql_fetch_row (table_info)) != NULL) { answer='\0'; printf ( "%s: ", row[0] ); scanf ( "%[^\n]%*c", &answer ); if ( answer == 'y') { printf ( "*****\n" ); fflush(stdout); table_name[index] = malloc ( strlen(row[0]) + 1 ); printf ( "*****\n" ); fflush(stdout); memcpy ( &table_name[index], &row[0], strlen(row[0]) + 1 ); } printf ( "finally inserted: %s \n", table_name[index]); fflush(stdout); } Result: 1_time_access: y ***** ./set-env.sh: line 17: 15263 Segmentation fault (core dumped) ./exec dataset_one (do not worry about set-env.sh, it is the script running th program.) I canot understand why this is happening.

    Read the article

  • Compression Program in C

    - by Delandilon
    I want to compress a series of characters. For example if i type Input : FFFFFBBBBBBBCCBBBAABBGGGGGSSS (27 x 8 bits = 216 bits) Output: F5B7C2B3A2B2G5S3 (14 x 8 bits = 112bits) So far this is what i have, i can count the number of Characters in the Array. But the most important task is to count them in the same sequence. I can't seem to figure that out :( Ive stared doing C just a few weeks back, i have knowledge on Array, pointers, ASCII value but in any case can't seem to count these characters in a sequence. Ive try a bit of everything. This approach is no good but it the closest i came to it. #include <stdio.h> #include <conio.h> int main() { int charcnt=0,dotcnt=0,commacnt=0,blankcnt=0,i, countA, countB; char str[125]; printf("*****String Manipulations*****\n\n"); printf("Enter a string\n\n"); scanf("%[^'\n']s",str); printf("\n\nEntered String is \" %s \" \n",str); for(i=0;str[i]!='\0';i++) { // COUNTING EXCEPTION CHARS if(str[i]==' ') blankcnt++; if(str[i]=='.') dotcnt++; if(str[i]==',') commacnt++; if (str[i]=='A' || str[i]=='a') countA++; if (str[i]=='B' || str[i]=='b') countA++; } //PRINT RESULT OF COUNT charcnt=i; printf("\n\nTotal Characters : %d",charcnt); printf("\nTotal Blanks : %d",blankcnt); printf("\nTotal Full stops : %d",dotcnt); printf("\nTotal Commas : %d\n\n",commacnt); printf("A%d\n", countA); }

    Read the article

  • Write a signal handler to catch SIGSEGV

    - by Adi
    Hi all, I want to write a signal handler to catch SIGSEGV. First , I would protect a block of memory for read or writes using char *buffer; char *p; char a; int pagesize = 4096; " mprotect(buffer,pagesize,PROT_NONE) " What this will do is , it will protect the memory starting from buffer till pagesize for any reads or writes. Second , I will try to read the memory by doing something like p = buffer; a = *p This will generate a SIGSEGV and i have initialized a handler for this. The handler will be called . So far so good. Now the problem I am facing is , once the handler is called, I want to change the access write of the memory by doing mprotect(buffer, pagesize,PROT_READ); and continue my normal functioning of the code. I do not want to exit the function. On future writes to the same memory, I want again catch the signal and modify the write rights and then take account of that event. Here is the code I am trying : #include <signal.h> #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <errno.h> #include <sys/mman.h> #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) char *buffer; int flag=0; static void handler(int sig, siginfo_t *si, void *unused) { printf("Got SIGSEGV at address: 0x%lx\n",(long) si->si_addr); printf("Implements the handler only\n"); flag=1; //exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { char *p; char a; int pagesize; struct sigaction sa; sa.sa_flags = SA_SIGINFO; sigemptyset(&sa.sa_mask); sa.sa_sigaction = handler; if (sigaction(SIGSEGV, &sa, NULL) == -1) handle_error("sigaction"); pagesize=4096; /* Allocate a buffer aligned on a page boundary; initial protection is PROT_READ | PROT_WRITE */ buffer = memalign(pagesize, 4 * pagesize); if (buffer == NULL) handle_error("memalign"); printf("Start of region: 0x%lx\n", (long) buffer); printf("Start of region: 0x%lx\n", (long) buffer+pagesize); printf("Start of region: 0x%lx\n", (long) buffer+2*pagesize); printf("Start of region: 0x%lx\n", (long) buffer+3*pagesize); //if (mprotect(buffer + pagesize * 0, pagesize,PROT_NONE) == -1) if (mprotect(buffer + pagesize * 0, pagesize,PROT_NONE) == -1) handle_error("mprotect"); //for (p = buffer ; ; ) if(flag==0) { p = buffer+pagesize/2; printf("It comes here before reading memory\n"); a = *p; //trying to read the memory printf("It comes here after reading memory\n"); } else { if (mprotect(buffer + pagesize * 0, pagesize,PROT_READ) == -1) handle_error("mprotect"); a = *p; printf("Now i can read the memory\n"); } /* for (p = buffer;p<=buffer+4*pagesize ;p++ ) { //a = *(p); *(p) = 'a'; printf("Writing at address %p\n",p); }*/ printf("Loop completed\n"); /* Should never happen */ exit(EXIT_SUCCESS); } The problem I am facing with this is ,only the signal handler is running and I am not able to return to the main function after catching the signal.. Any help in this will be greatly appreciated. Thanks in advance Aditya

    Read the article

  • Strange thing on IPv6 multicast program on Windows

    - by zhanglistar
    I have written an ipv6 multicast program on windows xp sp3. But a problem bothers me a lot. The sendto function implies no error, but I can't capture the packet using wireshark. I am sure the filter is right. Thanks in advance. And the code is as follows: #include "stdafx.h" #include <stdio.h> /* for printf() and fprintf() */ #include <winsock2.h> /* for socket(), connect(), sendto(), and recvfrom() */ #include <ws2tcpip.h> /* for ip_mreq */ #include <stdlib.h> /* for atoi() and exit() */ #include <string.h> /* for memset() */ #include <time.h> /* for timestamps */ #include <pcap.h> #include <Iphlpapi.h> #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "wpcap.lib") #pragma comment(lib, "Iphlpapi.lib") int _tmain(int argc, _TCHAR* argv[]) { int sfd; int on, length, iResult; WSADATA wsaData; struct addrinfo Hints; struct addrinfo *multicastAddr, *localAddr; char buf[46]; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); return 1; } /* Resolve destination address for multicast datagrams */ memset(&Hints, 0, sizeof (Hints)); Hints.ai_family = AF_INET6; Hints.ai_socktype = SOCK_DGRAM; Hints.ai_protocol = IPPROTO_UDP; Hints.ai_flags = AI_NUMERICHOST; iResult = getaddrinfo("FF02::1:2", "547", &Hints, &multicastAddr); if (iResult != 0) { /* error handling */ printf("socket error: %d\n", WSAGetLastError()); return -1; } /* Get a local address with the same family (IPv4 or IPv6) as our multicast group */ Hints.ai_family = multicastAddr->ai_family; Hints.ai_socktype = SOCK_DGRAM; Hints.ai_flags = AI_PASSIVE; /* Return an address we can bind to */ if ( getaddrinfo(NULL, "546", &Hints, &localAddr) != 0 ) { printf("getaddrinfo() failed: %d\n", WSAGetLastError()); exit(-1); } // Create sending socket //sfd = socket (multicastAddr->ai_family, multicastAddr->ai_socktype, multicastAddr->ai_protocol); sfd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); if (sfd == -1) { printf("socket error: %d\n", WSAGetLastError()); return 0; } /* Bind to the multicast port */ if ( bind(sfd, localAddr->ai_addr, localAddr->ai_addrlen) != 0 ) { printf("bind() failed: %d\n", WSAGetLastError()); exit(-1); } if (multicastAddr->ai_family == AF_INET6 && multicastAddr->ai_addrlen == sizeof(struct sockaddr_in6)) /* IPv6 */ { on = 1; if (setsockopt (sfd, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *)&on, sizeof (on) /*(char *)&interface_addr, sizeof(interface_addr)*/) == -1) { printf("setsockopt error:%d\n", WSAGetLastError()); return -1; } if (setsockopt (sfd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&on, sizeof (on) /*(char *)&interface_addr, sizeof(interface_addr)*/) == -1) { printf("setsockopt error:%d\n", WSAGetLastError()); return -1; } struct ipv6_mreq multicastRequest; /* Multicast address join structure */ /* Specify the multicast group */ memcpy(&multicastRequest.ipv6mr_multiaddr, &((struct sockaddr_in6*)(multicastAddr->ai_addr))->sin6_addr, sizeof(struct in6_addr)); /* Accept multicast from any interface */ multicastRequest.ipv6mr_interface = 0; /* Join the multicast address */ if ( setsockopt(sfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, (char*) &multicastRequest, sizeof(multicastRequest)) != 0 ) { printf("setsockopt() failed: %d\n", WSAGetLastError()); return -1; } on = 1; if (setsockopt (sfd, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *)&on, sizeof (on)) == -1) { printf("setsockopt error:%d\n", WSAGetLastError()); return 0; } } memset(buf, 0, sizeof(buf)); strcpy(buf, "hello world"); iResult = sendto(sfd, buf, strlen(buf), 0, (LPSOCKADDR) multicastAddr->ai_addr, multicastAddr->ai_addrlen); if (iResult == SOCKET_ERROR) { printf("setsockopt error:%d\n", WSAGetLastError()); return -1; /* Error handling */ } return 0; }

    Read the article

  • Runtime error in C code (strange double conversion)

    - by Miro Hassan
    I have a strange runtime error in my C code. The Integers comparison here works fine. But in the Decimals comparison, I always get that the second number is larger than the first number, which is false. I am pretty new to C and programming in general, so this is a complex application to me. #include <stdio.h> #include <stdbool.h> #include <stdlib.h> int choose; long long neLimit = -1000000000; long long limit = 1000000000; bool big(a,b) { if ((a >= limit) || (b >= limit)) return true; else if ((a <= neLimit) || (b <= neLimit)) return true; return false; } void largerr(a,b) { if (a > b) printf("\nThe First Number is larger ..\n"); else if (a < b) printf("\nThe Second Number is larger ..\n"); else printf("\nThe Two Numbers are Equal .. \n"); } int main() { system("color e && title Numbers Comparison && echo off && cls"); start:{ printf("Choose a Type of Comparison :\n\t1. Integers\n\t2. Decimals \n\t\t I Choose Number : "); scanf("%i", &choose); switch(choose) { case 1: goto Integers; break; case 2: goto Decimals; break; default: system("echo Please Choose a Valid Option && pause>nul && cls"); goto start; } } Integers: { system("title Integers Comparison && cls"); long x , y; printf("\nFirst Number : \t"); scanf("%li", &x); printf("\nSecond Number : "); scanf("%li", &y); if (big(x,y)) { printf("\nOut of Limit .. Too Big Numbers ..\n"); system("pause>nul && cls") ; goto Integers; } largerr(x,y); printf("\nFirst Number : %li\nSecond Number : %li\n",x,y); goto exif; } Decimals: { system("title Decimals Comparison && cls"); double x , y; printf("\nFirst Number : \t"); scanf("%le", &x); printf("\nSecond Number : "); scanf("%le", &y); if (big(x,y)) { printf("\nOut of Limit .. Too Big Numbers ..\n"); system("pause>nul && cls") ; goto Decimals; } largerr(x,y); goto exif; } exif:{ system("pause>nul"); system("cls"); main(); } }

    Read the article

  • Streamed mp3 only plays for 1 second

    - by angel6
    Hi, I'm using the plaympeg.c (modified) code of smpeg as a media player. I've got ffserver running as a streaming server. I'm a streaming an mp3 file over http. But when I run plaympeg.c, it plays the streamed file only for a second. When I run plaympeg again, it starts off from where it left and plays for 1 second. Does anyone know why this happens an how to fix it? I've tested it out on WMP and it plays the entire file in one go. So, i guess it's not a problem with the streaming or ffserver.conf include include include include /* #ifdef unix */ include include include include include include include define NET_SUPPORT /* General network support */ define HTTP_SUPPORT /* HTTP support */ ifdef NET_SUPPORT include include include include endif include "smpeg.h" ifdef NET_SUPPORT int tcp_open(char * address, int port) { struct sockaddr_in stAddr; struct hostent * host; int sock; struct linger l; memset(&stAddr,0,sizeof(stAddr)); stAddr.sin_family = AF_INET ; stAddr.sin_port = htons(port); if((host = gethostbyname(address)) == NULL) return(0); stAddr.sin_addr = *((struct in_addr *) host-h_addr_list[0]) ; if((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) return(0); l.l_onoff = 1; l.l_linger = 5; if(setsockopt(sock, SOL_SOCKET, SO_LINGER, (char*) &l, sizeof(l)) < 0) return(0); if(connect(sock, (struct sockaddr *) &stAddr, sizeof(stAddr)) < 0) return(0); return(sock); } ifdef HTTP_SUPPORT int http_open(char * arg) { char * host; int port; char * request; int tcp_sock; char http_request[1024]; char c; printf("\nin http_open passed parameter = %s\n",arg); /* Check for URL syntax */ if(strncmp(arg, "http://", strlen("http://"))) return(0); /* Parse URL */ port = 80; host = arg + strlen("http://"); if((request = strchr(host, '/')) == NULL) return(0); request++ = 0; if(strchr(host, ':') != NULL) / port is specified */ { port = atoi(strchr(host, ':') + 1); *strchr(host, ':') = 0; } /* Open a TCP socket */ if(!(tcp_sock = tcp_open(host, port))) { perror("http_open"); return(0); } /* Send HTTP GET request */ sprintf(http_request, "GET /%s HTTP/1.0\r\n" "User-Agent: Mozilla/2.0 (Win95; I)\r\n" "Pragma: no-cache\r\n" "Host: %s\r\n" "Accept: /\r\n" "\r\n", request, host); send(tcp_sock, http_request, strlen(http_request), 0); /* Parse server reply */ do read(tcp_sock, &c, sizeof(char)); while(c != ' '); read(tcp_sock, http_request, 4*sizeof(char)); http_request[4] = 0; if(strcmp(http_request, "200 ")) { fprintf(stderr, "http_open: "); do { read(tcp_sock, &c, sizeof(char)); fprintf(stderr, "%c", c); } while(c != '\r'); fprintf(stderr, "\n"); return(0); } return(tcp_sock); } endif endif void update(SDL_Surface *screen, Sint32 x, Sint32 y, Uint32 w, Uint32 h) { if ( screen-flags & SDL_DOUBLEBUF ) { SDL_Flip(screen); } } /* Flag telling the UI that the movie or song should be skipped */ int done; void next_movie(int sig) { done = 1; } int main(int argc, char *argv[]) { int use_audio, use_video; int fullscreen; int scalesize; int scale_width, scale_height; int loop_play; int i, pause; int volume; Uint32 seek; float skip; int bilinear_filtering; SDL_Surface *screen; SMPEG *mpeg; SMPEG_Info info; char *basefile; SDL_version sdlver; SMPEG_version smpegver; int fd; char buf[32]; int status; printf("\nchecking command line options "); /* Get the command line options */ use_audio = 1; use_video = 1; fullscreen = 0; scalesize = 1; scale_width = 0; scale_height = 0; loop_play = 0; volume = 100; seek = 0; skip = 0; bilinear_filtering = 0; fd = 0; for ( i=1; argv[i] && (argv[i][0] == '-') && (argv[i][1] != 0); ++i ) { if ( strcmp(argv[i], "--fullscreen") == 0 ) { fullscreen = 1; } else if ((strcmp(argv[i], "--seek") == 0)||(strcmp(argv[i], "-S") == 0)) { ++i; if ( argv[i] ) { seek = atol(argv[i]); } } else if ((strcmp(argv[i], "--volume") == 0)||(strcmp(argv[i], "-v") == 0)) { ++i; if (i >= argc) { fprintf(stderr, "Please specify volume when using --volume or -v\n"); return(1); } if ( argv[i] ) { volume = atoi(argv[i]); } if ( ( volume < 0 ) || ( volume 100 ) ) { fprintf(stderr, "Volume must be between 0 and 100\n"); volume = 100; } } else { fprintf(stderr, "Warning: Unknown option: %s\n", argv[i]); } } printf("\nuse video = %d, use audio = %d\n",use_video, use_audio); printf("\ngoing to check input parameters\n"); if defined(linux) || defined(FreeBSD) /* Plaympeg doesn't need a mouse */ putenv("SDL_NOMOUSE=1"); endif /* Play the mpeg files! */ status = 0; for ( ; argv[i]; ++i ) { /* Initialize SDL */ if ( use_video ) { if ((SDL_Init(SDL_INIT_VIDEO) < 0) || !SDL_VideoDriverName(buf, 1)) { fprintf(stderr, "Warning: Couldn't init SDL video: %s\n", SDL_GetError()); fprintf(stderr, "Will ignore video stream\n"); use_video = 0; } printf("\ninitialised video\n"); } if ( use_audio ) { if ((SDL_Init(SDL_INIT_AUDIO) < 0) || !SDL_AudioDriverName(buf, 1)) { fprintf(stderr, "Warning: Couldn't init SDL audio: %s\n", SDL_GetError()); fprintf(stderr, "Will ignore audio stream\n"); use_audio = 0; } } /* Allow Ctrl-C when there's no video output */ signal(SIGINT, next_movie); printf("\nchecking defined supports\n"); /* Create the MPEG stream */ ifdef NET_SUPPORT printf("\ndefined NET_SUPPORT\n"); ifdef HTTP_SUPPORT printf("\ndefined HTTP_SUPPORT\n"); /* Check if source is an http URL */ printf("\nabout to call http_open\n"); printf("\nhere we go\n"); if((fd = http_open(argv[i])) != 0) mpeg = SMPEG_new_descr(fd, &info, use_audio); else endif endif { if(strcmp(argv[i], "-") == 0) /* Use stdin for input */ mpeg = SMPEG_new_descr(0, &info, use_audio); else mpeg = SMPEG_new(argv[i], &info, use_audio); } if ( SMPEG_error(mpeg) ) { fprintf(stderr, "%s: %s\n", argv[i], SMPEG_error(mpeg)); SMPEG_delete(mpeg); status = -1; continue; } SMPEG_enableaudio(mpeg, use_audio); SMPEG_enablevideo(mpeg, use_video); SMPEG_setvolume(mpeg, volume); /* Print information about the video */ basefile = strrchr(argv[i], '/'); if ( basefile ) { ++basefile; } else { basefile = argv[i]; } if ( info.has_audio && info.has_video ) { printf("%s: MPEG system stream (audio/video)\n", basefile); } else if ( info.has_audio ) { printf("%s: MPEG audio stream\n", basefile); } else if ( info.has_video ) { printf("%s: MPEG video stream\n", basefile); } if ( info.has_video ) { printf("\tVideo %dx%d resolution\n", info.width, info.height); } if ( info.has_audio ) { printf("\tAudio %s\n", info.audio_string); } if ( info.total_size ) { printf("\tSize: %d\n", info.total_size); } if ( info.total_time ) { printf("\tTotal time: %f\n", info.total_time); } /* Set up video display if needed */ if ( info.has_video && use_video ) { const SDL_VideoInfo *video_info; Uint32 video_flags; int video_bpp; int width, height; /* Get the "native" video mode */ video_info = SDL_GetVideoInfo(); switch (video_info->vfmt->BitsPerPixel) { case 16: case 24: case 32: video_bpp = video_info->vfmt->BitsPerPixel; break; default: video_bpp = 16; break; } if ( scale_width ) { width = scale_width; } else { width = info.width; } width *= scalesize; if ( scale_height ) { height = scale_height; } else { height = info.height; } height *= scalesize; video_flags = SDL_SWSURFACE; if ( fullscreen ) { video_flags = SDL_FULLSCREEN|SDL_DOUBLEBUF|SDL_HWSURFACE; } video_flags |= SDL_ASYNCBLIT; video_flags |= SDL_RESIZABLE; screen = SDL_SetVideoMode(width, height, video_bpp, video_flags); if ( screen == NULL ) { fprintf(stderr, "Unable to set %dx%d video mode: %s\n", width, height, SDL_GetError()); continue; } SDL_WM_SetCaption(argv[i], "plaympeg"); if ( screen->flags & SDL_FULLSCREEN ) { SDL_ShowCursor(0); } SMPEG_setdisplay(mpeg, screen, NULL, update); SMPEG_scaleXY(mpeg, screen->w, screen->h); } else { SDL_QuitSubSystem(SDL_INIT_VIDEO); } /* Set any special playback parameters */ if ( loop_play ) { SMPEG_loop(mpeg, 1); } /* Seek starting position */ if(seek) SMPEG_seek(mpeg, seek); /* Skip seconds to starting position */ if(skip) SMPEG_skip(mpeg, skip); /* Play it, and wait for playback to complete */ SMPEG_play(mpeg); done = 0; pause = 0; while ( ! done && ( pause || (SMPEG_status(mpeg) == SMPEG_PLAYING) ) ) { SDL_Event event; while ( use_video && SDL_PollEvent(&event) ) { switch (event.type) { case SDL_VIDEORESIZE: { SDL_Surface *old_screen = screen; SMPEG_pause(mpeg); screen = SDL_SetVideoMode(event.resize.w, event.resize.h, screen->format->BitsPerPixel, screen->flags); if ( old_screen != screen ) { SMPEG_setdisplay(mpeg, screen, NULL, update); } SMPEG_scaleXY(mpeg, screen-w, screen-h); SMPEG_pause(mpeg); } break; case SDL_KEYDOWN: if ( (event.key.keysym.sym == SDLK_ESCAPE) || (event.key.keysym.sym == SDLK_q) ) { // Quit done = 1; } else if ( event.key.keysym.sym == SDLK_RETURN ) { // toggle fullscreen if ( event.key.keysym.mod & KMOD_ALT ) { SDL_WM_ToggleFullScreen(screen); fullscreen = (screen-flags & SDL_FULLSCREEN); SDL_ShowCursor(!fullscreen); } } else if ( event.key.keysym.sym == SDLK_UP ) { // Volume up if ( volume < 100 ) { if ( event.key.keysym.mod & KMOD_SHIFT ) { // 10+ volume += 10; } else if ( event.key.keysym.mod & KMOD_CTRL ) { // 100+ volume = 100; } else { // 1+ volume++; } if ( volume 100 ) volume = 100; SMPEG_setvolume(mpeg, volume); } } else if ( event.key.keysym.sym == SDLK_DOWN ) { // Volume down if ( volume 0 ) { if ( event.key.keysym.mod & KMOD_SHIFT ) { volume -= 10; } else if ( event.key.keysym.mod & KMOD_CTRL ) { volume = 0; } else { volume--; } if ( volume < 0 ) volume = 0; SMPEG_setvolume(mpeg, volume); } } else if ( event.key.keysym.sym == SDLK_PAGEUP ) { // Full volume volume = 100; SMPEG_setvolume(mpeg, volume); } else if ( event.key.keysym.sym == SDLK_PAGEDOWN ) { // Volume off volume = 0; SMPEG_setvolume(mpeg, volume); } else if ( event.key.keysym.sym == SDLK_SPACE ) { // Toggle play / pause if ( SMPEG_status(mpeg) == SMPEG_PLAYING ) { SMPEG_pause(mpeg); pause = 1; } else { SMPEG_play(mpeg); pause = 0; } } else if ( event.key.keysym.sym == SDLK_RIGHT ) { // Forward if ( event.key.keysym.mod & KMOD_SHIFT ) { SMPEG_skip(mpeg, 100); } else if ( event.key.keysym.mod & KMOD_CTRL ) { SMPEG_skip(mpeg, 50); } else { SMPEG_skip(mpeg, 5); } } else if ( event.key.keysym.sym == SDLK_LEFT ) { // Reverse if ( event.key.keysym.mod & KMOD_SHIFT ) { } else if ( event.key.keysym.mod & KMOD_CTRL ) { } else { } } else if ( event.key.keysym.sym == SDLK_KP_MINUS ) { // Scale minus if ( scalesize > 1 ) { scalesize--; } } else if ( event.key.keysym.sym == SDLK_KP_PLUS ) { // Scale plus scalesize++; } else if ( event.key.keysym.sym == SDLK_f ) { // Toggle filtering on/off if ( bilinear_filtering ) { SMPEG_Filter *filter = SMPEGfilter_null(); filter = SMPEG_filter( mpeg, filter ); filter-destroy(filter); bilinear_filtering = 0; } else { SMPEG_Filter *filter = SMPEGfilter_bilinear(); filter = SMPEG_filter( mpeg, filter ); filter-destroy(filter); bilinear_filtering = 1; } } break; case SDL_QUIT: done = 1; break; default: break; } } SDL_Delay(1000/2); } SMPEG_delete(mpeg); } SDL_Quit(); if defined(HTTP_SUPPORT) if(fd) close(fd); endif return(status); }

    Read the article

  • Help debugging c fifos code - stack smashing detected - open call not functioning - removing pipes

    - by nunos
    I have three bugs/questions regarding the source code pasted below: stack smashing deteced: In order to compile and not have that error I have addedd the gcc compile flag -fno-stack-protector. However, this should be just a temporary solution, since I would like to find where the cause for this is and correct it. However, I haven't been able to do so. Any clues? For some reason, the last open function call doesn't work and the programs just stops there, without an error, even though the fifo already exists. I want to delete the pipes from the filesystem after before terminating the processes. I have added close and unlink statements at the end, but the fifos are not removed. What am I doing wrong? Thanks very much in advance. P.S.: I am pasting here the whole source file for additional clarity. Just ignore the comments, since they are in my own native language. server.c: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #define MAX_INPUT_LENGTH 100 #define FIFO_NAME_MAX_LEN 20 #define FIFO_DIR "/tmp/" #define FIFO_NAME_CMD_CLI_TO_SRV "lrc_cmd_cli_to_srv" typedef enum { false, true } bool; bool background = false; char* logfile = NULL; void read_from_fifo(int fd, char** var) { int n_bytes; read(fd, &n_bytes, sizeof(int)); *var = (char *) malloc (n_bytes); read(fd, *var, n_bytes); printf("read %d bytes '%s'\n", n_bytes, *var); } void write_to_fifo(int fd, char* data) { int n_bytes = (strlen(data)+1) * sizeof(char); write(fd, &n_bytes, sizeof(int)); //primeiro envia o numero de bytes que a proxima instrucao write ira enviar write(fd, data, n_bytes); printf("writing %d bytes '%s'\n", n_bytes, data); } int main(int argc, char* argv[]) { //CRIA FIFO CMD_CLI_TO_SRV, se ainda nao existir char* fifo_name_cmd_cli_to_srv; fifo_name_cmd_cli_to_srv = (char*) malloc ( (strlen(FIFO_NAME_CMD_CLI_TO_SRV) + strlen(FIFO_DIR) + 1) * sizeof(char) ); strcpy(fifo_name_cmd_cli_to_srv, FIFO_DIR); strcat(fifo_name_cmd_cli_to_srv, FIFO_NAME_CMD_CLI_TO_SRV); int n = mkfifo(fifo_name_cmd_cli_to_srv, 0660); //TODO ver permissoes if (n < 0 && errno != EEXIST) //se houver erro, e nao for por causa de ja haver um com o mesmo nome, termina o programa { fprintf(stderr, "erro ao criar o fifo\n"); fprintf(stderr, "errno: %d\n", errno); exit(4); } //se por acaso já existir, nao cria o fifo e continua o programa normalmente //le informacao enviada pelo cliente, nesta ordem: //1. pid (em formato char*) do processo cliente //2. comando /CONNECT //3. nome de fifo INFO_SRV_TO_CLIXXX //4. nome de fifo MSG_SRV_TO_CLIXXX char* command; char* fifo_name_info_srv_to_cli; char* fifo_name_msg_srv_to_cli; char* client_pid_string; int client_pid; int fd_cmd_cli_to_srv, fd_info_srv_to_cli; fd_cmd_cli_to_srv = open(fifo_name_cmd_cli_to_srv, O_RDONLY); read_from_fifo(fd_cmd_cli_to_srv, &client_pid_string); client_pid = atoi(client_pid_string); read_from_fifo(fd_cmd_cli_to_srv, &command); //recebe commando /CONNECT read_from_fifo(fd_cmd_cli_to_srv, &fifo_name_info_srv_to_cli); //recebe nome de fifo INFO_SRV_TO_CLIXXX read_from_fifo(fd_cmd_cli_to_srv, &fifo_name_msg_srv_to_cli); //recebe nome de fifo MSG_TO_SRV_TO_CLIXXX //CIRA FIFO MSG_CLIXXX_TO_SRV char fifo_name_msg_cli_to_srv[FIFO_NAME_MAX_LEN]; strcpy(fifo_name_msg_cli_to_srv, FIFO_DIR); strcat(fifo_name_msg_cli_to_srv, "lrc_msg_cli"); strcat(fifo_name_msg_cli_to_srv, client_pid_string); strcat(fifo_name_msg_cli_to_srv, "_to_srv"); n = mkfifo(fifo_name_msg_cli_to_srv, 0660); if (n < 0) { fprintf(stderr, "error creating %s\n", fifo_name_msg_cli_to_srv); fprintf(stderr, "errno: %d\n", errno); exit(5); } //envia ao cliente a resposta ao commando /CONNECT fd_info_srv_to_cli = open(fifo_name_info_srv_to_cli, O_WRONLY); write_to_fifo(fd_info_srv_to_cli, fifo_name_msg_cli_to_srv); free(logfile); free(fifo_name_cmd_cli_to_srv); close(fd_cmd_cli_to_srv); unlink(fifo_name_cmd_cli_to_srv); unlink(fifo_name_msg_cli_to_srv); unlink(fifo_name_msg_srv_to_cli); unlink(fifo_name_info_srv_to_cli); printf("fim\n"); return 0; } client.c: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #define MAX_INPUT_LENGTH 100 #define PID_BUFFER_LEN 10 #define FIFO_NAME_CMD_CLI_TO_SRV "lrc_cmd_cli_to_srv" #define FIFO_NAME_INFO_SRV_TO_CLI "lrc_info_srv_to_cli" #define FIFO_NAME_MSG_SRV_TO_CLI "lrc_msg_srv_to_cli" #define COMMAND_MAX_LEN 100 #define FIFO_DIR "/tmp/" typedef enum { false, true } bool; char* nickname; char* name; char* email; void write_to_fifo(int fd, char* data) { int n_bytes = (strlen(data)+1) * sizeof(char); write(fd, &n_bytes, sizeof(int)); //primeiro envia o numero de bytes que a proxima instrucao write ira enviar write(fd, data, n_bytes); printf("writing %d bytes '%s'\n", n_bytes, data); } void read_from_fifo(int fd, char** var) { int n_bytes; read(fd, &n_bytes, sizeof(int)); *var = (char *) malloc (n_bytes); printf("read '%s'\n", *var); read(fd, *var, n_bytes); } int main(int argc, char* argv[]) { pid_t pid = getpid(); //CRIA FIFO INFO_SRV_TO_CLIXXX char pid_string[PID_BUFFER_LEN]; sprintf(pid_string, "%d", pid); char* fifo_name_info_srv_to_cli; fifo_name_info_srv_to_cli = (char *) malloc ( (strlen(FIFO_DIR) + strlen(FIFO_NAME_INFO_SRV_TO_CLI) + strlen(pid_string) + 1 ) * sizeof(char) ); strcpy(fifo_name_info_srv_to_cli, FIFO_DIR); strcat(fifo_name_info_srv_to_cli, FIFO_NAME_INFO_SRV_TO_CLI); strcat(fifo_name_info_srv_to_cli, pid_string); int n = mkfifo(fifo_name_info_srv_to_cli, 0660); if (n < 0) { fprintf(stderr, "error creating %s\n", fifo_name_info_srv_to_cli); fprintf(stderr, "errno: %d\n", errno); exit(6); } int fd_cmd_cli_to_srv, fd_info_srv_to_cli; fd_cmd_cli_to_srv = open("/tmp/lrc_cmd_cli_to_srv", O_WRONLY); char command[COMMAND_MAX_LEN]; printf("> "); scanf("%s", command); while (strcmp(command, "/CONNECT")) { printf("O primeiro comando deverá ser \"/CONNECT\"\n"); printf("> "); scanf("%s", command); } //CRIA FIFO MSG_SRV_TO_CLIXXX char* fifo_name_msg_srv_to_cli; fifo_name_msg_srv_to_cli = (char *) malloc ( (strlen(FIFO_DIR) + strlen(FIFO_NAME_MSG_SRV_TO_CLI) + strlen(pid_string) + 1) * sizeof(char) ); strcpy(fifo_name_msg_srv_to_cli, FIFO_DIR); strcat(fifo_name_msg_srv_to_cli, FIFO_NAME_MSG_SRV_TO_CLI); strcat(fifo_name_msg_srv_to_cli, pid_string); n = mkfifo(fifo_name_msg_srv_to_cli, 0660); if (n < 0) { fprintf(stderr, "error creating %s\n", fifo_name_info_srv_to_cli); fprintf(stderr, "errno: %d\n", errno); exit(7); } // ENVIA COMANDO /CONNECT write_to_fifo(fd_cmd_cli_to_srv, pid_string); //envia pid do processo cliente write_to_fifo(fd_cmd_cli_to_srv, command); //envia commando /CONNECT write_to_fifo(fd_cmd_cli_to_srv, fifo_name_info_srv_to_cli); //envia nome de fifo INFO_SRV_TO_CLIXXX write_to_fifo(fd_cmd_cli_to_srv, fifo_name_msg_srv_to_cli); //envia nome de fifo MSG_TO_SRV_TO_CLIXXX // recebe do servidor a resposta ao comanddo /CONNECT printf("msg1\n"); printf("vamos tentar abrir %s\n", fifo_name_info_srv_to_cli); fd_info_srv_to_cli = open(fifo_name_info_srv_to_cli, O_RDONLY); printf("%s aberto", fifo_name_info_srv_to_cli); if (fd_info_srv_to_cli < 0) { fprintf(stderr, "erro ao criar %s\n", fifo_name_info_srv_to_cli); fprintf(stderr, "errno: %d\n", errno); } printf("msg2\n"); char* fifo_name_msg_cli_to_srv; printf("msg3\n"); read_from_fifo(fd_info_srv_to_cli, &fifo_name_msg_cli_to_srv); printf("msg4\n"); free(nickname); free(name); free(email); free(fifo_name_info_srv_to_cli); free(fifo_name_msg_srv_to_cli); unlink(fifo_name_msg_srv_to_cli); unlink(fifo_name_info_srv_to_cli); printf("fim\n"); return 0; } makefile: CC = gcc CFLAGS = -Wall -lpthread -fno-stack-protector all: client server client: client.c $(CC) $(CFLAGS) client.c -o client server: server.c $(CC) $(CFLAGS) server.c -o server clean: rm -f client server *~

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >