Search Results

Search found 1466 results on 59 pages for 'sizeof'.

Page 11/59 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • execl doesn't work in a while(1) cicle, server side; C script

    - by Possa
    Hi guys, I have a problem with a little C script who should run as a server and launch a popup for every message arriving. The execl syntax is correct because if I try a little script with main() { execl(...); } it works. When I put it in a while(1) cicle it doesn't work. Everything else is working, like printf or string operation, but not the execl. Even if I fork it doesn't work. I really don't know what I can do ... can anyone help me? Thanks in advice for your help and sorry for my bad english. Here's the complete server C code. #include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <string.h> #define BUFLEN 512 #define PORT 9930 void diep(char *s) { perror(s); exit(1); } int main() { struct sockaddr_in si_me, si_other; int s, i, slen=sizeof(si_other), broadcastPermission; char buf[100], zeni[BUFLEN]; if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) diep("socket"); broadcastPermission = 1; if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, (void *) &broadcastPermission, sizeof(broadcastPermission)) < 0) diep("setsockopt() failed"); memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(PORT); si_me.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(s, &si_me, sizeof(si_me))==-1) diep("bind"); while (1) { if (recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)==-1) diep("recvfrom()"); //printf("Received packet from %s:%d\nData: %s\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf); strcpy(zeni, ""); strcat(zeni, "zenity --warning --title Hack!! --text "); strcat(zeni, buf); printf("cmd: %s\n", zeni); //system (zeni); execl("/usr/bin/zenity", "/usr/bin/zenity", "--warning", "--title", "Warn!", "--text", buf, (char *) NULL); } close(s); return 0; }

    Read the article

  • matrix multiplication with MPI [on hold]

    - by user3695701
    I'm working on an assignment on matrix multiplication with MPI. A*B=C. the requirement is that B should be vertically partitioned. Here's what I intend to do: broadcast matrix A to all processes and scatter B into several slices with each slice containing n/p columns. The following code only works when the number of process(p) is 1. when p1(say 2), I got [cluster2:21080] *** Process received signal *** [cluster2:21080] Signal: Segmentation fault (11) [cluster2:21080] Signal code: Address not mapped (1) [cluster2:21080] Failing at address: (nil) [cluster2:21080] [ 0] /lib/libpthread.so.0(+0xf8f0) [0x7f49f38108f0] [cluster2:21080] [ 1] /lib/libc.so.6(memcpy+0xe1) [0x7f49f35024c1] [cluster2:21080] [ 2] /usr/lib/libmpi.so.0(ompi_convertor_unpack+0x121)[0x7f49f47c88e1] [cluster2:21080] [ 3] /usr/lib/openmpi/lib/openmpi/mca_pml_ob1.so(+0x8a26) [0x7f49f0dcea26] [cluster2:21080] [ 4] /usr/lib/openmpi/lib/openmpi/mca_btl_tcp.so(+0x662c) [0x7f49efce462c] [cluster2:21080] [ 5] /usr/lib/libopen-pal.so.0(+0x1ede8) [0x7f49f42e0de8] [cluster2:21080] [ 6] /usr/lib/libopen-pal.so.0(opal_progress+0x99) [0x7f49f42d5369] [cluster2:21080] [ 7] /usr/lib/openmpi/lib/openmpi/mca_pml_ob1.so(+0x5585) [0x7f49f0dcb585] [cluster2:21080] [ 8] /usr/lib/openmpi/lib/openmpi/mca_coll_tuned.so(+0xcc01) [0x7f49eeeb1c01] [cluster2:21080] [ 9] /usr/lib/openmpi/lib/openmpi/mca_coll_tuned.so(+0x266c) [0x7f49eeea766c] [cluster2:21080] [10] /usr/lib/openmpi/lib/openmpi/mca_coll_sync.so(+0x1388) [0x7f49ef0c0388] [cluster2:21080] [11] /usr/lib/libmpi.so.0(MPI_Bcast+0x10e) [0x7f49f47d025e] [cluster2:21080] [12] ./out(main+0x259) [0x401571] [cluster2:21080] [13] /lib/libc.so.6(__libc_start_main+0xfd) [0x7f49f3498c8d] [cluster2:21080] [14] ./out() [0x400f29] [cluster2:21080] *** End of error message *** Can someone help me? Thanks. //matrices A and B //double* A =(double *)malloc(n*n*sizeof(double)); //double* B =(double *)malloc(n*n*sizeof(double)); //code initializing A,B... //n is the size of the matrix //p is the number of processes //myrank is the rank of calling process MPI_Init (&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); MPI_Comm_size(MPI_COMM_WORLD, &p); //broadcast A to all processes MPI_Bcast (A, n*n, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Datatype tmp_type, col_type; // extract a slice from B MPI_Type_vector(n, num_of_col_per_slice, n, MPI_DOUBLE, &tmp_type); // position of the first (0) and each next (stride * sizeof(double) ) slice MPI_Type_create_resized(tmp_type, 0, n * sizeof(double), &col_type); MPI_Type_commit(&col_type); //scatter a slice of B to each process MPI_Scatter(B, 1, col_type, B+myrank*n/p, n * n/p, MPI_DOUBLE, 0, MPI_COMM_WORLD); //use blas function to calculate A*sliceOfB and store the resulting slice to C cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, n/p, n, 1.0, A, n, B+myrank*n/p, n, 0.0, C+myrank*n/p, n); //gather all those resulting slices into C MPI_Gather (C+myrank*n/p, n*n/p, MPI_DOUBLE, C, n*n/p, MPI_DOUBLE, 0, MPI_COMM_WORLD);

    Read the article

  • C: copying some structs causes strange behavior

    - by Jenny B
    I have an annoying bug in the line rq->tickets[rq->usedContracts] = toAdd; if i do: rq->tickets[0] = toAdd the program crashes if i do rq->tickets[1] = toAdd; it works valgrind says ==19501== Use of uninitialised value of size 8 and ==19501== Invalid write of size 8 for this very line. What is wrong? struct TS_element { int travels; int originalTravels; int cost; char** dates; int moneyLeft; } TicketSet; struct RQ_element { int usedContracts; struct TS_element* tickets; } RabQav; TicketSetStatus tsCreate(TicketSet* t, int n, int c) { if (n <= 0) return TS_ILLEGAL_PARAMETER; TicketSet* myTicketSet = (TicketSet*) malloc(sizeof(TicketSet)); if (myTicketSet == NULL) { return TS_CANNOT_CREATE; } myTicketSet->usedTravels = 0; myTicketSet->originalTravels = n; myTicketSet->cost = c; myTicketSet->moneyLeft = n * c; char** dates = malloc(sizeof(char**)* (n)); //todo maybe c99 allows dynamic arrays? for (int i = 0; i < n; i++) { dates[i] = malloc(sizeof(char)*GOOD_LENGTH+1); if (dates[i] == NULL) { free(dates); free(t); return TS_CANNOT_CREATE; } } myTicketSet->dates = dates; *t = *myTicketSet; return TS_SUCCESS; } static void copyTicketSets(TicketSet* dest, const TicketSet* source) { dest->usedTravels = source->usedTravels; dest->originalTravels = source->originalTravels; dest->cost = source->cost; dest->moneyLeft = source->moneyLeft; for (int i = 0; i < source->originalTravels; i++) { if (NULL != source->dates[i]) { free(dest->dates[i]); dest->dates[i] = malloc(sizeof(char) * GOOD_LENGTH + 1); if (dest->dates[i] == NULL) { free(dest->dates); //todo free dates 0...i-1 free(dest); return; } strcpy(dest->dates[i], source->dates[i]); } } } RabQavStatus rqLoadTS(RabQav* rq, TicketSet t, DateTime dt) { TicketSet toAdd; TicketSetStatus res = tsCreate(&toAdd, t.originalTravels, t.cost); if (res != TS_SUCCESS) { return RQ_FAIL; } copyTicketSets(&toAdd, &t); rq->tickets[rq->usedContracts] = toAdd; rq->usedContracts++; return RQ_SUCCESS; }

    Read the article

  • CUDA memory transfer issue

    - by Vaibhav Sundriyal
    I am trying to execute a code which first transfers data from CPU to GPU memory and vice-versa. In spite of increasing the volume of data, the data transfer time remains the same as if no data transfer is actually taking place. I am posting the code. #include <stdio.h> /* Core input/output operations */ #include <stdlib.h> /* Conversions, random numbers, memory allocation, etc. */ #include <math.h> /* Common mathematical functions */ #include <time.h> /* Converting between various date/time formats */ #include <cuda.h> /* CUDA related stuff */ #include <sys/time.h> __global__ void device_volume(float *x_d,float *y_d) { int index = blockIdx.x * blockDim.x + threadIdx.x; } int main(void) { float *x_h,*y_h,*x_d,*y_d,*z_h,*z_d; long long size=9999999; long long nbytes=size*sizeof(float); timeval t1,t2; double et; x_h=(float*)malloc(nbytes); y_h=(float*)malloc(nbytes); z_h=(float*)malloc(nbytes); cudaMalloc((void **)&x_d,size*sizeof(float)); cudaMalloc((void **)&y_d,size*sizeof(float)); cudaMalloc((void **)&z_d,size*sizeof(float)); gettimeofday(&t1,NULL); cudaMemcpy(x_d, x_h, nbytes, cudaMemcpyHostToDevice); cudaMemcpy(y_d, y_h, nbytes, cudaMemcpyHostToDevice); cudaMemcpy(z_d, z_h, nbytes, cudaMemcpyHostToDevice); gettimeofday(&t2,NULL); et = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms et += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms printf("\n %ld\t\t%f\t\t",nbytes,et); et=0.0; //printf("%f %d\n",seconds,CLOCKS_PER_SEC); // launch a kernel with a single thread to greet from the device //device_volume<<<1,1>>>(x_d,y_d); gettimeofday(&t1,NULL); cudaMemcpy(x_h, x_d, nbytes, cudaMemcpyDeviceToHost); cudaMemcpy(y_h, y_d, nbytes, cudaMemcpyDeviceToHost); cudaMemcpy(z_h, z_d, nbytes, cudaMemcpyDeviceToHost); gettimeofday(&t2,NULL); et = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms et += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms printf("%f\n",et); cudaFree(x_d); cudaFree(y_d); cudaFree(z_d); return 0; } Can anybody help me with this issue? Thanks

    Read the article

  • How to copy the memeory allocated in device function back to main memory

    - by xhe8
    I have a CUDA program containing a host function and a device function Execute(). In the host function, I allocate a global memory output which will then be passed to the device function and used to store the address of the global memory allocated within the device function. I want to access the in-kernel allocated memory in the host function. The following is the code: #include <stdio.h> typedef struct { int * p; int num; } Structure_A; \__global__ void Execute(Structure_A *output); int main(){ Structure_A *output; cudaMalloc((void***)&output,sizeof(Structure_A)*1); dim3 dimBlockExecute(1,1); dim3 dimGridExecute(1,1); Execute<<<dimGridExecute,dimBlockExecute>>>(output); Structure_A * output_cpu; int * p_cpu; cudaError_t err; output_cpu= (Structure_A*)malloc(1); err=cudaMemcpy(output_cpu,output,sizeof(Structure_A),cudaMemcpyDeviceToHost); if( err != cudaSuccess) { printf("CUDA error a: %s\n", cudaGetErrorString(err)); exit(-1); } p_cpu=(int *)malloc(1); err=cudaMemcpy(p_cpu,output_cpu[0].p,sizeof(int),cudaMemcpyDeviceToHost); if( err != cudaSuccess) { printf("CUDA error b: %s\n", cudaGetErrorString(err)); exit(-1); } printf("output=(%d,%d)\n",output_cpu[0].num,p_cpu[0]); return 0; } \__global__ void Execute(Structure_A *output){ int thid=threadIdx.x; output[thid].p= (int*)malloc(thid+1); output[thid].num=(thid+1); output[thid].p[0]=5; } I can compile the program. But when I run it, I got a error showing that there is a invalid argument in the following memory copy function. "err=cudaMemcpy(p_cpu,output_cpu[0].p,sizeof(int),cudaMemcpyDeviceToHost);" CUDA version is 4.2. CUDA card: Tesla C2075 OS: x86_64 GNU/Linux

    Read the article

  • GLSL: Strange light reflections

    - by Tom
    According to this tutorial I'm trying to make a normal mapping using GLSL, but something is wrong and I can't find the solution. The output render is in this image: Image1 in this image is a plane with two triangles and each of it is different illuminated (that is bad). The plane has 6 vertices. In the upper left side of this plane are 2 identical vertices (same in the lower right). Here are some vectors same for each vertice: normal vector = 0, 1, 0 (red lines on image) tangent vector = 0, 0,-1 (green lines on image) bitangent vector = -1, 0, 0 (blue lines on image) here I have one question: The two identical vertices does need to have the same tangent and bitangent? I have tried to make other values to the tangents but the effect was still similar. Here are my shaders Vertex shader: #version 130 // Input vertex data, different for all executions of this shader. in vec3 vertexPosition_modelspace; in vec2 vertexUV; in vec3 vertexNormal_modelspace; in vec3 vertexTangent_modelspace; in vec3 vertexBitangent_modelspace; // Output data ; will be interpolated for each fragment. out vec2 UV; out vec3 Position_worldspace; out vec3 EyeDirection_cameraspace; out vec3 LightDirection_cameraspace; out vec3 LightDirection_tangentspace; out vec3 EyeDirection_tangentspace; // Values that stay constant for the whole mesh. uniform mat4 MVP; uniform mat4 V; uniform mat4 M; uniform mat3 MV3x3; uniform vec3 LightPosition_worldspace; void main(){ // Output position of the vertex, in clip space : MVP * position gl_Position = MVP * vec4(vertexPosition_modelspace,1); // Position of the vertex, in worldspace : M * position Position_worldspace = (M * vec4(vertexPosition_modelspace,1)).xyz; // Vector that goes from the vertex to the camera, in camera space. // In camera space, the camera is at the origin (0,0,0). vec3 vertexPosition_cameraspace = ( V * M * vec4(vertexPosition_modelspace,1)).xyz; EyeDirection_cameraspace = vec3(0,0,0) - vertexPosition_cameraspace; // Vector that goes from the vertex to the light, in camera space. M is ommited because it's identity. vec3 LightPosition_cameraspace = ( V * vec4(LightPosition_worldspace,1)).xyz; LightDirection_cameraspace = LightPosition_cameraspace + EyeDirection_cameraspace; // UV of the vertex. No special space for this one. UV = vertexUV; // model to camera = ModelView vec3 vertexTangent_cameraspace = MV3x3 * vertexTangent_modelspace; vec3 vertexBitangent_cameraspace = MV3x3 * vertexBitangent_modelspace; vec3 vertexNormal_cameraspace = MV3x3 * vertexNormal_modelspace; mat3 TBN = transpose(mat3( vertexTangent_cameraspace, vertexBitangent_cameraspace, vertexNormal_cameraspace )); // You can use dot products instead of building this matrix and transposing it. See References for details. LightDirection_tangentspace = TBN * LightDirection_cameraspace; EyeDirection_tangentspace = TBN * EyeDirection_cameraspace; } Fragment shader: #version 130 // Interpolated values from the vertex shaders in vec2 UV; in vec3 Position_worldspace; in vec3 EyeDirection_cameraspace; in vec3 LightDirection_cameraspace; in vec3 LightDirection_tangentspace; in vec3 EyeDirection_tangentspace; // Ouput data out vec3 color; // Values that stay constant for the whole mesh. uniform sampler2D DiffuseTextureSampler; uniform sampler2D NormalTextureSampler; uniform sampler2D SpecularTextureSampler; uniform mat4 V; uniform mat4 M; uniform mat3 MV3x3; uniform vec3 LightPosition_worldspace; void main(){ // Light emission properties // You probably want to put them as uniforms vec3 LightColor = vec3(1,1,1); float LightPower = 40.0; // Material properties vec3 MaterialDiffuseColor = texture2D( DiffuseTextureSampler, vec2(UV.x,-UV.y) ).rgb; vec3 MaterialAmbientColor = vec3(0.1,0.1,0.1) * MaterialDiffuseColor; //vec3 MaterialSpecularColor = texture2D( SpecularTextureSampler, UV ).rgb * 0.3; vec3 MaterialSpecularColor = vec3(0.5,0.5,0.5); // Local normal, in tangent space. V tex coordinate is inverted because normal map is in TGA (not in DDS) for better quality vec3 TextureNormal_tangentspace = normalize(texture2D( NormalTextureSampler, vec2(UV.x,-UV.y) ).rgb*2.0 - 1.0); // Distance to the light float distance = length( LightPosition_worldspace - Position_worldspace ); // Normal of the computed fragment, in camera space vec3 n = TextureNormal_tangentspace; // Direction of the light (from the fragment to the light) vec3 l = normalize(LightDirection_tangentspace); // Cosine of the angle between the normal and the light direction, // clamped above 0 // - light is at the vertical of the triangle -> 1 // - light is perpendicular to the triangle -> 0 // - light is behind the triangle -> 0 float cosTheta = clamp( dot( n,l ), 0,1 ); // Eye vector (towards the camera) vec3 E = normalize(EyeDirection_tangentspace); // Direction in which the triangle reflects the light vec3 R = reflect(-l,n); // Cosine of the angle between the Eye vector and the Reflect vector, // clamped to 0 // - Looking into the reflection -> 1 // - Looking elsewhere -> < 1 float cosAlpha = clamp( dot( E,R ), 0,1 ); color = // Ambient : simulates indirect lighting MaterialAmbientColor + // Diffuse : "color" of the object MaterialDiffuseColor * LightColor * LightPower * cosTheta / (distance*distance) + // Specular : reflective highlight, like a mirror MaterialSpecularColor * LightColor * LightPower * pow(cosAlpha,5) / (distance*distance); //color.xyz = E; //color.xyz = LightDirection_tangentspace; //color.xyz = EyeDirection_tangentspace; } I have replaced the original color value by EyeDirection_tangentspace vector and then I got other strange effect but I can not link the image (not eunogh reputation) Is it possible that with this shaders is something wrong, or maybe in other place in my code e.g with my matrices? SOLVED Solved... 3 days needed for changing one letter from this: glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer ( 4, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? sizeof(VboVertex), // stride (void*)(12*sizeof(float)) // array buffer offset ); to this: glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexAttribPointer ( 4, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? sizeof(VboVertex), // stride (void*)(11*sizeof(float)) // array buffer offset ); see difference? :)

    Read the article

  • What's the best/most efficent way to create a semi-intelligent AI for a tic tac toe game?

    - by Link
    basically I am attempting to make a a efficient/smallish C game of Tic-Tac-Toe. I have implemented everything other then the AI for the computer so far. my squares are basically structs in an array with an assigned value based on the square. For example s[1].value = 1; therefore it's a x, and then a value of 3 would be a o. My question is whats the best way to create a semi-decent game playing AI for my tic-tac-toe game? I don't really want to use minimax, since It's not what I need. So how do I avoid a a lot of if statments and make it more efficient. Here is the rest of my code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> struct state{ // defined int state; // 0 is tie, 1 is user loss, 2 is user win, 3 is ongoing game int moves; }; struct square{ // one square of the board int value; // 1 is x, 3 is o char sign; // no space used }; struct square s[9]; //set up the struct struct state gamestate = {0,0}; //nothing void setUpGame(){ // setup the game int i = 0; for(i = 0; i < 9; i++){ s[i].value = 0; s[i].sign = ' '; } gamestate.moves=0; printf("\nHi user! You're \"x\"! I'm \"o\"! Good Luck :)\n"); } void displayBoard(){// displays the game board printf("\n %c | %c | %c\n", s[6].sign, s[7].sign, s[8].sign); printf("-----------\n"); printf(" %c | %c | %c\n", s[3].sign, s[4].sign, s[5].sign); printf("-----------\n"); printf(" %c | %c | %c\n\n", s[0].sign, s[1].sign, s[2].sign); } void getHumanMove(){ // get move from human int i; while(1){ printf(">>:"); char line[255]; // input the move to play fgets(line, sizeof(line), stdin); while(sscanf(line, "%d", &i) != 1) { //1 match of defined specifier on input line printf("Sorry, that's not a valid move!\n"); fgets(line, sizeof(line), stdin); } if(s[i-1].value != 0){printf("Sorry, That moves already been taken!\n\n");continue;} break; } s[i-1].value = 1; s[i-1].sign = 'x'; gamestate.moves++; } int sum(int x, int y, int z){return(x*y*z);} void getCompMove(){ // get the move from the computer } void checkWinner(){ // check the winner int i; for(i = 6; i < 9; i++){ // check cols if((sum(s[i].value,s[i-3].value,s[i-6].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;} if((sum(s[i].value,s[i-3].value,s[i-6].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;} } for(i = 0; i < 7; i+=3){ // check rows if((sum(s[i].value,s[i+1].value,s[i+2].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;} if((sum(s[i].value,s[i+1].value,s[i+2].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;} } if((sum(s[0].value,s[4].value,s[8].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;} if((sum(s[0].value,s[4].value,s[8].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;} if((sum(s[2].value,s[4].value,s[6].value)) == 8){printf("The Winner is o!\n");gamestate.state=1;} if((sum(s[2].value,s[4].value,s[6].value)) == 1){printf("The Winner is x!\n");gamestate.state=2;} } void playGame(){ // start playing the game gamestate.state = 3; //set-up the gamestate srand(time(NULL)); int temp = (rand()%2) + 1; if(temp == 2){ // if two comp goes first temp = (rand()%2) + 1; if(temp == 2){ s[4].value = 2; s[4].sign = 'o'; gamestate.moves++; }else{ s[2].value = 2; s[2].sign = 'o'; gamestate.moves++; } } displayBoard(); while(gamestate.state == 3){ if(gamestate.moves<10); getHumanMove(); if(gamestate.moves<10); getCompMove(); checkWinner(); if(gamestate.state == 3 && gamestate.moves==9){ printf("The game is a tie :p\n"); break; } displayBoard(); } } int main(int argc, const char *argv[]){ printf("Welcome to Tic Tac Toe\nby The Elite Noob\nEnter 1-9 To play a move, standard numpad\n1 is bottom-left, 9 is top-right\n"); while(1){ // while game is being played printf("\nPress 1 to play a new game, or any other number to exit;\n>>:"); char line[255]; // input whether or not to play the game fgets(line, sizeof(line), stdin); int choice; // user's choice about playing or not while(sscanf(line, "%d", &choice) != 1) { //1 match of defined specifier on input line printf("Sorry, that's not a valid option!\n"); fgets(line, sizeof(line), stdin); } if(choice == 1){ setUpGame(); // set's up the game playGame(); // Play a Game }else {break;} // exit the application } printf("\nThank's For playing!\nHave a good Day!\n"); return 0; }

    Read the article

  • C -Segmentation fault !

    - by FILIaS
    It seems at least weird to me... The program runs normally.But after I call the enter() function for the 4th time,there is a segmentation fault!I would appreciate any help. With the following function enter() I wanna add user commands' datas to a list. [Some part of the code is already posted on another question of me, but I think I should post it again...as it's a different problem I'm facing now.] /* struct for all the datas that user enters on file*/ typedef struct catalog { char short_name[50]; char surname[50]; signed int amount; char description[1000]; struct catalog *next; }catalog,*catalogPointer; catalogPointer current; catalogPointer head = NULL; void enter(void) //user command: i <name> <surname> <amount> <description> { int n,j=2,k=0; char temp[1500]; char *short_name,*surname,*description; signed int amount; char* params = strchr(command,' ') + 1; //strchr returns a pointer to the 1st space on the command.U want a pointer to the char right after that space. strcpy(temp, params); //params is saved as temp. char *curToken = strtok(temp," "); //strtok cuts 'temp' into strings between the spaces and saves them to 'curToken' printf("temp is:%s \n",temp); printf("\nWhat you entered for saving:\n"); for (n = 0; curToken; ++n) //until curToken ends: { if (curToken) { short_name = malloc(strlen(curToken) + 1); strncpy(short_name, curToken, sizeof (short_name)); } printf("Short Name: %s \n",short_name); curToken = strtok(NULL," "); if (curToken) { surname = malloc(strlen(curToken) + 1); strncpy(surname, curToken,sizeof (surname)); } printf("SurName: %s \n",surname); curToken = strtok(NULL," "); if (curToken) { //int * amount= malloc(sizeof (signed int *)); char *chk; amount = (int) strtol(curToken, &chk, 10); if (!isspace(*chk) && *chk != 0) fprintf(stderr,"Warning: expected integer value for amount, received %s instead\n",curToken); } printf("Amount: %d \n",amount); curToken = strtok(NULL,"\0"); if (curToken) { description = malloc(strlen(curToken) + 1); strncpy(description, curToken, sizeof (description)); } printf("Description: %s \n",description); break; } if (findEntryExists(head, surname,short_name) != NULL) //call function in order to see if entry exists already on the catalog printf("\nAn entry for <%s %s> is already in the catalog!\nNew entry not entered.\n",short_name,surname); else { printf("\nTry to entry <%s %s %d %s> in the catalog list!\n",short_name,surname,amount,description); newEntry(&head,short_name,surname,amount,description); printf("\n**Entry done!**\n"); } // Maintain the list in alphabetical order by surname. } catalogPointer findEntryExists (catalogPointer head, char num[],char first[]) { catalogPointer p = head; while (p != NULL && strcmp(p->surname, num) != 0 && strcmp(p->short_name,first) != 0) { p = p->next; } return p; } catalogPointer newEntry (catalog** headRef,char short_name[], char surname[], signed int amount, char description[]) { catalogPointer newNode = (catalogPointer)malloc(sizeof(catalog)); catalogPointer first; catalogPointer second; catalogPointer tmp; first=head; second=NULL; strcpy(newNode->short_name, short_name); strcpy(newNode->surname, surname); newNode->amount=amount; strcpy(newNode->description, description); while (first!=NULL) { if (strcmp(surname,first->surname)>0) second=first; else if (strcmp(surname,first->surname)==0) { if (strcmp(short_name,first->short_name)>0) second=first; } first=first->next; } if (second==NULL) { newNode->next=head; head=newNode; } else //SEGMENTATION APPEARS WHEN IT GETS HERE! { tmp=second->next; newNode->next=tmp; first->next=newNode; } } UPDATE: SegFault appears only when it gets on the 'else' loop of InsertSort() function. I observed that segmentation fault appears when i try to put on the list names that are after it. For example, if in the list exists: [Name:b Surname:b Amount:6 Description:b] [Name:c Surname:c Amount:5 Description:c] [Name:d Surname:d Amount:4 Description:d] [Name:e Surname:e Amount:3 Description:e] [Name:g Surname:g Amount:2 Description:g] [Name:x Surname:x Amount:1 Description:x] and i put: " x z 77 gege" there is a segmentation but if i put "x a 77 gege" it continues normally....

    Read the article

  • C -Segmentation fault after the 4th call of the function!

    - by FILIaS
    It seems at least weird to me... The program runs normally.But after I call the enter() function for the 4th time,there is a segmentation fault!I would appreciate any help. With the following function enter() I wanna add user commands' datas to a list. [Some part of the code is already posted on another question of me, but I think I should post it again...as it's a different problem I'm facing now.] /* struct for all the datas that user enters on file*/ typedef struct catalog { char short_name[50]; char surname[50]; signed int amount; char description[1000]; struct catalog *next; }catalog,*catalogPointer; catalogPointer current; catalogPointer head = NULL; void enter(void) //user command: i <name> <surname> <amount> <description> { int n,j=2,k=0; char temp[1500]; char *short_name,*surname,*description; signed int amount; char* params = strchr(command,' ') + 1; //strchr returns a pointer to the 1st space on the command.U want a pointer to the char right after that space. strcpy(temp, params); //params is saved as temp. char *curToken = strtok(temp," "); //strtok cuts 'temp' into strings between the spaces and saves them to 'curToken' printf("temp is:%s \n",temp); printf("\nWhat you entered for saving:\n"); for (n = 0; curToken; ++n) //until curToken ends: { if (curToken) { short_name = malloc(strlen(curToken) + 1); strncpy(short_name, curToken, sizeof (short_name)); } printf("Short Name: %s \n",short_name); curToken = strtok(NULL," "); if (curToken) { surname = malloc(strlen(curToken) + 1); strncpy(surname, curToken,sizeof (surname)); } printf("SurName: %s \n",surname); curToken = strtok(NULL," "); if (curToken) { //int * amount= malloc(sizeof (signed int *)); char *chk; amount = (int) strtol(curToken, &chk, 10); if (!isspace(*chk) && *chk != 0) fprintf(stderr,"Warning: expected integer value for amount, received %s instead\n",curToken); } printf("Amount: %d \n",amount); curToken = strtok(NULL,"\0"); if (curToken) { description = malloc(strlen(curToken) + 1); strncpy(description, curToken, sizeof (description)); } printf("Description: %s \n",description); break; } if (findEntryExists(head, surname,short_name) != NULL) //call function in order to see if entry exists already on the catalog printf("\nAn entry for <%s %s> is already in the catalog!\nNew entry not entered.\n",short_name,surname); else { printf("\nTry to entry <%s %s %d %s> in the catalog list!\n",short_name,surname,amount,description); newEntry(&head,short_name,surname,amount,description); printf("\n**Entry done!**\n"); } // Maintain the list in alphabetical order by surname. } catalogPointer findEntryExists (catalogPointer head, char num[],char first[]) { catalogPointer p = head; while (p != NULL && strcmp(p->surname, num) != 0 && strcmp(p->short_name,first) != 0) { p = p->next; } return p; } catalogPointer newEntry (catalog** headRef,char short_name[], char surname[], signed int amount, char description[]) { catalogPointer newNode = (catalogPointer)malloc(sizeof(catalog)); catalogPointer first; catalogPointer second; catalogPointer tmp; first=head; second=NULL; strcpy(newNode->short_name, short_name); strcpy(newNode->surname, surname); newNode->amount=amount; strcpy(newNode->description, description); //SEGMENTATION ON THE 4TH RUN OF PROGRAM STOPS HERE depending on the names each time it gets! while (first!=NULL) { if (strcmp(surname,first->surname)>0) second=first; else if (strcmp(surname,first->surname)==0) { if (strcmp(short_name,first->short_name)>0) second=first; } first=first->next; } if (second==NULL) { newNode->next=head; head=newNode; } else { tmp=second->next; newNode->next=tmp; first->next=newNode; } }

    Read the article

  • c windows connect() fails. error 10049

    - by Joshua Moore
    The following two pieces of code compile, but I get a connect() failed error on the client side. (compiled with MinGW). Client Code: // thanks to cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoClientWS.c #include <stdio.h> #include <winsock.h> #include <stdlib.h> #define RCVBUFSIZE 32 // size of receive buffer void DieWithError(char *errorMessage); int main(int argc, char* argv[]) { int sock; struct sockaddr_in echoServAddr; unsigned short echoServPort; char *servIP; char *echoString; char echoBuffer[RCVBUFSIZE]; int echoStringLen; int bytesRcvd, totalBytesRcvd; WSAData wsaData; if((argc < 3) || (argc > 4)){ fprintf(stderr, "Usage: %s <Sever IP> <Echo Word> [<Echo Port>]\n", argv[0]); exit(1); } if (argc==4) echoServPort = atoi(argv[3]); // use given port if any else echoServPort = 7; // echo is well-known port for echo service if(WSAStartup(MAKEWORD(2, 0), &wsaData) != 0){ // load winsock 2.0 dll fprintf(stderr, "WSAStartup() failed"); exit(1); } // create reliable, stream socket using tcp if((sock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("socket() failed"); // construct the server address structure memset(&echoServAddr, 0, sizeof(echoServAddr)); echoServAddr.sin_family = AF_INET; echoServAddr.sin_addr.s_addr = inet_addr(servIP); // server IP address echoServAddr.sin_port = htons(echoServPort); // establish connection to the echo server if(connect(sock, (struct sockaddr*)&echoServAddr, sizeof(echoServAddr)) < 0) DieWithError("connect() failed"); echoStringLen = strlen(echoString); // determine input length // send the string, includeing the null terminator to the server if(send(sock, echoString, echoStringLen, 0)!= echoStringLen) DieWithError("send() sent a different number of bytes than expected"); totalBytesRcvd = 0; printf("Received: "); // setup to print the echoed string while(totalBytesRcvd < echoStringLen){ // receive up to the buffer size (minus 1 to leave space for a null terminator) bytes from the sender if(bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE-1, 0) <= 0) DieWithError("recv() failed or connection closed prematurely"); totalBytesRcvd += bytesRcvd; // keep tally of total bytes echoBuffer[bytesRcvd] = '\0'; printf("%s", echoBuffer); // print the echo buffer } printf("\n"); closesocket(sock); WSACleanup(); exit(0); } void DieWithError(char *errorMessage) { fprintf(stderr, "%s: %d\n", errorMessage, WSAGetLastError()); exit(1); } Server Code: // thanks cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoServerWS.c #include <stdio.h> #include <winsock.h> #include <stdlib.h> #define MAXPENDING 5 // maximum outstanding connection requests #define RCVBUFSIZE 1000 void DieWithError(char *errorMessage); void HandleTCPClient(int clntSocket); // tcp client handling function int main(int argc, char **argv) { int serverSock; int clientSock; struct sockaddr_in echoServerAddr; struct sockaddr_in echoClientAddr; unsigned short echoServerPort; int clientLen; // length of client address data structure WSAData wsaData; if (argc!=2){ fprintf(stderr, "Usage: %s <Server Port>\n", argv[0]); exit(1); } echoServerPort = atoi(argv[1]); if(WSAStartup(MAKEWORD(2, 0), &wsaData)!=0){ fprintf(stderr, "WSAStartup() failed"); exit(1); } // create socket for incoming connections if((serverSock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))<0) DieWithError("socket() failed"); // construct local address structure memset(&echoServerAddr, 0, sizeof(echoServerAddr)); echoServerAddr.sin_family = AF_INET; echoServerAddr.sin_addr.s_addr = htonl(INADDR_ANY); // any incoming interface echoServerAddr.sin_port = htons(echoServerPort); // local port // bind to the local address if(bind(serverSock, (struct sockaddr*)&echoServerAddr, sizeof(echoServerAddr) )<0) DieWithError("bind() failed"); // mark the socket so it will listen for incoming connections if(listen(serverSock, MAXPENDING)<0) DieWithError("listen() failed"); for (;;){ // run forever // set the size of the in-out parameter clientLen = sizeof(echoClientAddr); // wait for a client to connect if((clientSock = accept(serverSock, (struct sockaddr*)&echoClientAddr, &clientLen)) < 0) DieWithError("accept() failed"); // clientSock is connected to a client printf("Handling client %s\n", inet_ntoa(echoClientAddr.sin_addr)); HandleTCPClient(clientSock); } // NOT REACHED } void DieWithError(char *errorMessage) { fprintf(stderr, "%s: %d\n", errorMessage, WSAGetLastError()); exit(1); } void HandleTCPClient(int clientSocket) { char echoBuffer[RCVBUFSIZE]; // buffer for echostring int recvMsgSize; // size of received message // receive message from client if((recvMsgSize = recv(clientSocket, echoBuffer, RCVBUFSIZE, 0) <0)) DieWithError("recv() failed"); // send received string and receive again until end of transmission while(recvMsgSize > 0){ // echo message back to client if(send(clientSocket, echoBuffer, recvMsgSize, 0)!=recvMsgSize) DieWithError("send() failed"); // see if there's more data to receive if((recvMsgSize = recv(clientSocket, echoBuffer, RCVBUFSIZE, 0)) <0) DieWithError("recv() failed"); } closesocket(clientSocket); // close client socket } How can I fix this?

    Read the article

  • I'd like to know why a function executes fine when called from x but not when called from y

    - by Roland
    When called from archive(), readcont(char *filename) executes fine! Called from runoptions() though, it fails to list the files "archived"! why is this? The program must run in terminal. Use -h as a parameter to view the usage. This program is written to "archive" text files into ".rldzip" files. readcont( char *x) should show the files archived in file (*x) a) Successful call Use the program to archive 3 text files: rldzip.exe a.txt b.txt c.txt FILEXY -a archive() will call readcont and it will work showing the files archived after the binary FILEXY will be created. b) Unsuccessful call After the file is created, use: rldzip.exe FILEXY.rldzip -v You can see that the function crashes! I'd like to know why is this happening! /* Sa se scrie un program care: a) arhiveaza fisiere b) dezarhiveaza fisierele athivate */ #include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> struct content{ char *text; char *flname; }*arc; FILE *f; void readcont(char *x){ FILE *p; if((p = fopen(x, "rb")) == NULL){ perror("Critical error: "); exit(EXIT_FAILURE); } content aux; int i; fread(&i, sizeof(int), 1, p); printf("\nFiles in %s \n\n", x); while(i-- >1 && fread(&aux, sizeof(struct content), 1, p) != 0) printf("%s \n", aux.flname); fclose(p); printf("\n\n"); } void archive(int argc, char **argv){ int i; char inttext[5000], textline[1000]; //Allocate dynamic memory for the content to be archived! arc = (content*)malloc(argc * sizeof(content)); for(i=1; i< argc; i++) { if((f = fopen(argv[i], "r")) == NULL){ printf("%s: ", argv[i]); perror(""); exit(EXIT_FAILURE); } while(!feof(f)){ fgets(textline, 5000, f); strcat(inttext, textline); } arc[i-1].text = (char*)malloc(strlen(inttext) + 1); strcpy(arc[i-1].text, inttext); arc[i-1].flname = (char*)malloc(strlen(argv[i]) + 1); strcpy(arc[i-1].flname, argv[i]); fclose(f); } char *filen; filen=(char*)malloc(strlen(argv[argc])+1+7); strcpy(filen, argv[argc]); strcat(filen, ".rldzip"); f = fopen(filen, "wb"); fwrite(&argc, sizeof(int), 1, f); fwrite(arc, sizeof(content), argc, f); fclose(f); printf("Success! "); for(i=1; i< argc; i++) { (i==argc-1)? printf("and %s ", argv[i]) : printf("%s ", argv[i]); } printf("compressed into %s", filen); readcont(filen); free(filen); } void help(char *v){ printf("\n\n----------------------RLDZIP----------------------\n\nUsage: \n\n Archive n files: \n\n%s $file[1] $file[2] ... $file[n] $output -a\n\nExample:\n%s a.txt b.txt c.txt output -a\n\n\n\nView files:\n\n %s $file.rldzip -v\n\nExample:\n %s fileE.rldzip -v\n\n", v, v, v, v); } void runoptions(int c, char **v){ int i; if(c < 2){ printf("Arguments missing! Use -h for help"); } else{ for(i=0; i<c; i++) if(strcmp(v[i], "-h") == 0){ help(v[0]); exit(2); } for(i=0; i<c; i++) if(strcmp(v[i], "-v") == 0){ if(c != 3){ printf("Arguments misused! Use -h for help"); exit(2); } else { printf("-%s-", v[1]); readcont(v[1]); } } } if(strcmp(v[c-1], "-a") == 0) archive(c-2, v); } main(int argc, char **argv) { runoptions(argc, argv); }

    Read the article

  • C programming: hashtable insertion/search

    - by Ricardo Campos
    Hello i have a problem with my hash table its implemented like this: #define HT_SIZE 10 typedef struct _list_t_ { char key[20]; char string[20]; char prevValue[20]; struct _list_t_ *next; } list_t; typedef struct _hash_table_t_ { int size; /* the size of the table */ list_t ***table; /* first */ sem_t lock; } hash_table_t; I have a Linked list with 3 pointers because i want a hash table with several partitions (shards), here is my initialization of my Hash table: hash_table_t *create_hash_table(int NUM_SERVER_THREADS, int num_shards){ hash_table_t *new_table; int j,i; if (HT_SIZE<1) return NULL; /* invalid size for table */ /* Attempt to allocate memory for the hashtable structure */ new_table = (hash_table_t*)malloc(sizeof(hash_table_t)*HT_SIZE); /* Attempt to allocate memory for the table itself */ new_table->table = (list_t ***)calloc(1,sizeof(list_t **)); /* Initialize the elements of the table */ for(j=0; j<num_shards; j++){ new_table->table[j] = (list_t **)calloc(1,sizeof(list_t *)); for(i=0; i<HT_SIZE; i++){ new_table->table[j][i] = (list_t *)calloc(1,sizeof(list_t )); } } /* Set the table's size */ new_table->size = HT_SIZE; sem_init(&new_table->lock, 0, 1); return new_table; } Here is my search function to search in the hash table list_t *lookup_string(hash_table_t *hashtable, char *key, int shardId){ list_t *list ; int hashval = hash(key); /* Go to the correct list based on the hash value and see if key is * in the list. If it is, return return a pointer to the list element. * If it isn't, the item isn't in the table, so return NULL. */ sem_wait(&hashtable->lock); for(list = hashtable->table[shardId][hashval]; list != NULL; list =list->next) { if (strcmp(key, list->key) == 0){ sem_post(&hashtable->lock); return list; } } sem_post(&hashtable->lock); return NULL; } And my insert function: char *add_string(hash_table_t *hashtable, char *str,char *key, int shardId){ list_t *new_list; list_t *current_list; unsigned int hashval = hash(key); /*printf("|%d|%d|%s|\n",hashval,shardId,key);*/ /* Lock for concurrency */ sem_wait(&hashtable->lock); /* Attempt to allocate memory for list */ new_list = (list_t*)malloc(sizeof(list_t)); /* Does item already exist? */ sem_post(&hashtable->lock); current_list = lookup_string(hashtable, key,shardId); sem_wait(&hashtable->lock); /* item already exists, don't insert it again. */ if (current_list != NULL){ strcpy(new_list->prevValue,current_list->string); strcpy(new_list->string,str); strcpy(new_list->key,key); new_list->next = hashtable->table[shardId][hashval]; hashtable->table[shardId][hashval] = new_list; sem_post(&hashtable->lock); return new_list->prevValue; } /* Insert into list */ strcpy(new_list->string,str); strcpy(new_list->key,key); new_list->next = hashtable->table[shardId][hashval]; hashtable->table[shardId][hashval] = new_list; /* Unlock */ sem_post(&hashtable->lock); return new_list->prevValue; } My main class runs some of tests by executing the insertion / reading / delete from the elements of the hash table the problem is when i have more than 4 partitions/shards the tests stop at the first reading element saying it returned the wrong value NULL on the search function, when its less than 4 it runs perfectly well and passes all the tests. You can see my main.c in here if you want to give a look: http://hostcode.sourceforge.net/view/1105 My complete Hash table code: http://hostcode.sourceforge.net/view/1103 And other functions where hash table code is executed: .c file http://hostcode.sourceforge.net/view/1104 .h file http://hostcode.sourceforge.net/view/1106 Thank for you time, i appreciate any help you can give to me this is a college important project that I'm trying to solve and I'm stuck here for 2 days.

    Read the article

  • directX texture appears incorrectly

    - by numerical25
    I finally managed to get a texture onto a cube sadly, but it is appearing incorrectly. as the below picture identifies. Anyways, I am not sure what it could be. My first guess is it could be my uv mapping or my vertex positioning is off. If someone could check and make sure thats good. The first element is the vertex position, second is the color, and third is the uv texture. //Create vectors and put in vertices // Create vertex buffer VertexPos vertices[] = { // BACK SIDES { D3DXVECTOR3(-5.0f, 5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(-5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(1.0,1.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, { D3DXVECTOR3(-5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(1.0,1.0)}, { D3DXVECTOR3(5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(1.0,1.0)}, // 2 FRONT SIDE { D3DXVECTOR3(-5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f), D3DXVECTOR2(1.0,0.0)}, { D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, { D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, { D3DXVECTOR3(5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f) , D3DXVECTOR2(1.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f), D3DXVECTOR2(1.0,1.0)}, // 3 { D3DXVECTOR3(-5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(1.0,0.0)}, { D3DXVECTOR3(-5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, { D3DXVECTOR3(-5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,2.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(1.0,0.0)}, { D3DXVECTOR3(5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, // 4 { D3DXVECTOR3(-5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(1.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, { D3DXVECTOR3(5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, { D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(1.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, -5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, // 5 { D3DXVECTOR3(5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(1.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(0.0,1.0)}, { D3DXVECTOR3(5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(0.0,1.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(1.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, 5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(0.0,2.0)}, // 6 {D3DXVECTOR3(-5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, {D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(1.0,0.0)}, {D3DXVECTOR3(-5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, {D3DXVECTOR3(-5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, {D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(1.0,0.0)}, {D3DXVECTOR3(-5.0f, -5.0f, 5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, }; My second guess could be an error that I am receiving as I run the program. But I don't know where to begin with that. The following is the description of the error . D3D10: WARNING: ID3D10Device::Draw: Vertex Buffer at the input vertex slot 0 is not big enough for what the Draw*() call expects to traverse. This is OK, as reading off the end of the Buffer is defined to return 0. However the developer probably did not intend to make use of this behavior. [ EXECUTION WARNING #356: DEVICE_DRAW_VERTEX_BUFFER_TOO_SMALL ] Not sure what it could be. but where is my vertex layout description //Create Layout D3D10_INPUT_ELEMENT_DESC layout[] = { {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT, 0 , 0, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"COLOR",0,DXGI_FORMAT_R32G32B32A32_FLOAT, 0 , 12, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL",0,DXGI_FORMAT_R32G32B32A32_FLOAT, 0 , 28, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD",0, DXGI_FORMAT_R32G32_FLOAT, 0 , 44, D3D10_INPUT_PER_VERTEX_DATA, 0} }; UINT numElements = (sizeof(layout)/sizeof(layout[0])); modelObject.numVertices = sizeof(vertices)/sizeof(VertexPos); for(int i = 0; i < modelObject.numVertices; i += 3) { D3DXVECTOR3 out; D3DXVECTOR3 v1 = vertices[0 + i].pos; D3DXVECTOR3 v2 = vertices[1 + i].pos; D3DXVECTOR3 v3 = vertices[2 + i].pos; D3DXVECTOR3 u = v2 - v1; D3DXVECTOR3 v = v3 - v1; D3DXVec3Cross(&out, &u, &v); D3DXVec3Normalize(&out, &out); vertices[0 + i].normal = out; vertices[1 + i].normal = out; vertices[2 + i].normal = out; } //Create buffer desc D3D10_BUFFER_DESC bufferDesc; bufferDesc.Usage = D3D10_USAGE_DEFAULT; bufferDesc.ByteWidth = sizeof(VertexPos) * modelObject.numVertices; bufferDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; D3D10_SUBRESOURCE_DATA initData; initData.pSysMem = vertices; //Create the buffer HRESULT hr = mpD3DDevice->CreateBuffer(&bufferDesc, &initData, &modelObject.pVertexBuffer); if(FAILED(hr)) return false;

    Read the article

  • Preventing FIN_WAIT2 when closing socket

    - by patrickvacek
    I have a server program that connects to another program via a given socket, and in certain cases I need to close the connection and almost immediately re-open it on the same socket. This by and large works, except that I have to wait exactly one minute for the socket to reset. In the meantime, netstat indicates that the server sees the socket in FIN_WAIT2 and the client sees it as CLOSE_WAIT. I'm already using SO_REUSEADDR, which I thought would prevent the wait, but that isn't doing the trick. Setting SO_LINGER to zero also does not help. What else can I do to resolve this? Here are the relevant code snippets: SetUpSocket() { // Set up the socket and listen for a connection from the exelerate client. // Open a TCP/IP socket. m_baseSock = socket(PF_INET, SOCK_STREAM, IPPROTO_IP); if (m_baseSock < 0) { return XERROR; } // Set the socket options to reuse local addresses. int flag = 1; if (setsockopt(m_baseSock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) == -1) { return XERROR; } // Set the socket options to prevent lingering after closing the socket. //~ linger li = {1,0}; //~ if (setsockopt(m_baseSock, SOL_SOCKET, SO_LINGER, &li, sizeof(li)) == -1) //~ { //~ return XERROR; //~ } // Bind the socket to the address of the current host and our given port. struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(m_port); if (bind(m_baseSock, (struct sockaddr*)&addr, sizeof(addr)) != 0) { return XERROR; } // Tell the socket to listen for a connection from client. if (listen(m_baseSock, 4) != 0) { return XERROR; } return XSUCCESS; } ConnectSocket() { // Add the socket to a file descriptor set. fd_set readfds; FD_ZERO(&readfds); FD_SET(m_baseSock, &readfds); // Set timeout to ten seconds. Plenty of time. struct timeval timeout; timeout.tv_sec = 10; timeout.tv_usec = 0; // Check to see if the socket is ready for reading. int numReady = select(m_baseSock + 1, &readfds, NULL, NULL, &timeout); if (numReady > 0) { int flags = fcntl(m_baseSock, F_GETFL, 0); fcntl(m_baseSock, flags | O_NONBLOCK, 1); // Wait for a connection attempt from the client. Do not block - we shouldn't // need to since we just selected. m_connectedSock = accept(m_baseSock, NULL, NULL); if (m_connectedSock > 0) { m_failedSend = false; m_logout = false; // Spawn a thread to accept commands from client. CreateThread(&m_controlThread, ControlThread, (void *)&m_connectedSock); return XSUCCESS; } } return XERROR; } ControlThread(void *arg) { // Get the socket from the argument. socket sock = *((socket*)arg); while (true) { // Add the socket to a file descriptor set. fd_set readfds; FD_ZERO(&readfds); FD_SET(sock, &readfds); // Set timeout to ten seconds. Plenty of time. struct timeval timeout; timeout.tv_sec = 10; timeout.tv_usec = 0; // Check if there is any readable data on the socket. int num_ready = select(sock + 1, &readfds, NULL, NULL, &timeout); if (num_ready < 0) { return NULL; } // If there is data, read it. else if (num_ready > 0) { // Check the read buffer. xuint8 buf[128]; ssize_t size_read = recv(sock, buf, sizeof(buf)); if (size_read > 0) { // Get the message out of the buffer. char msg = *buf; if (msg == CONNECTED) { // Do some things... } // If we get the log-out message, log out. else if (msg == LOGOUT) { return NULL; } } } } // while return NULL; } ~Server() { // Close the sockets. if (m_baseSock != SOCKET_ERROR) { close(m_baseSock); m_baseSock = SOCKET_ERROR; } if (m_connectedSock != SOCKET_ERROR) { close(m_connectedSock); m_connectedSock = SOCKET_ERROR; } } SOCKET_ERROR is equal to -1. The server object gets destroyed, at which point the connection should close, and then recreated, at which point the SetUpSocket() and ConnectSocket() routines are called. So why do I have to wait a minute for the socket to clear? Any ideas would be appreaciated.

    Read the article

  • Sockets: Transport endpoint is not connected on send

    - by TheoretiCAL
    I'm trying to learn socket programming from http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html and am attempting to build a SOCK_STREAM client/server. My client: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #define SERVERPORT "4951" // the port users will be connecting to int main(int argc, char *argv[]) { int sockfd; struct addrinfo hints, *servinfo, *p; int rv; int numbytes; if (argc != 3) { fprintf(stderr,"usage: talker hostname message\n"); exit(1); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(argv[1], SERVERPORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and make a socket for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("talker: socket"); continue; if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } } break; } if (p == NULL) { fprintf(stderr, "talker: failed to bind socket\n"); return 2; } if ((numbytes = send(sockfd, argv[2], strlen(argv[2]), 0) == -1)) { perror("talker: send"); exit(1); } freeaddrinfo(servinfo); printf("talker: sent %d bytes to %s\n", numbytes, argv[1]); close(sockfd); return 0; } Server: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #define MYPORT "4951" // the port users will be connecting to #define MAXBUFLEN 100 static int backlog = 10; // get sockaddr, IPv4 or IPv6: void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } int main(void) { int sockfd; struct addrinfo hints, *servinfo, *p; int rv; int numbytes; int new_fd; socklen_t addr_size; struct sockaddr_storage their_addr; char buf[MAXBUFLEN]; char s[INET6_ADDRSTRLEN]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4 hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("listener: socket"); continue; } int yes=1; // lose the pesky "Address already in use" error message if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("listener: bind"); continue; } if (listen(sockfd,backlog) == -1){ close(sockfd); perror("listener:listen"); continue; } break; } if (p == NULL) { fprintf(stderr, "listener: failed to bind socket\n"); return 2; } freeaddrinfo(servinfo); printf("listener: waiting to recv..\n"); while(1){ addr_size = sizeof their_addr; if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size))==-1){ perror("accept"); exit(1); } if ((numbytes = recv(new_fd, buf, MAXBUFLEN-1 , 0) == -1)) { perror("recv"); exit(1); } printf("listener: got packet from %s\n", inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s)); printf("listener: packet is %d bytes long\n", numbytes); buf[numbytes] = '\0'; printf("listener: packet contains \"%s\"\n", buf); close(sockfd); } return 0; } Upon executing the client, I get " send: Transport endpoint is not connected" and I'm not sure where I went wrong. Thanks.

    Read the article

  • Direct3D11 and SharpDX - How to pass a model instance's world matrix as an input to a vertex shader

    - by Nathan Ridley
    Using Direct3D11, I'm trying to pass a matrix into my vertex shader from the instance buffer that is associated with a given model's vertices and I can't seem to construct my InputLayout without throwing an exception. The shader looks like this: cbuffer ConstantBuffer : register(b0) { matrix World; matrix View; matrix Projection; } struct VIn { float4 position: POSITION; matrix instance: INSTANCE; float4 color: COLOR; }; struct VOut { float4 position : SV_POSITION; float4 color : COLOR; }; VOut VShader(VIn input) { VOut output; output.position = mul(input.position, input.instance); output.position = mul(output.position, View); output.position = mul(output.position, Projection); output.color = input.color; return output; } The input layout looks like this: var elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("INSTANCE", 0, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }; InputLayout = new InputLayout(device, signature, elements); The buffer initialization looks like this: public ModelDeviceData(Model model, Device device) { Model = model; var vertices = Helpers.CreateBuffer(device, BindFlags.VertexBuffer, model.Vertices); var instances = Helpers.CreateBuffer(device, BindFlags.VertexBuffer, Model.Instances.Select(m => m.WorldMatrix).ToArray()); VerticesBufferBinding = new VertexBufferBinding(vertices, Utilities.SizeOf<ColoredVertex>(), 0); InstancesBufferBinding = new VertexBufferBinding(instances, Utilities.SizeOf<Matrix>(), 0); IndicesBuffer = Helpers.CreateBuffer(device, BindFlags.IndexBuffer, model.Triangles); } The buffer creation helper method looks like this: public static Buffer CreateBuffer<T>(Device device, BindFlags bindFlags, params T[] items) where T : struct { var len = Utilities.SizeOf(items); var stream = new DataStream(len, true, true); foreach (var item in items) stream.Write(item); stream.Position = 0; var buffer = new Buffer(device, stream, len, ResourceUsage.Default, bindFlags, CpuAccessFlags.None, ResourceOptionFlags.None, 0); return buffer; } The line that instantiates the InputLayout object throws this exception: *HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.* Note that the data for each model instance is simply an instance of SharpDX.Matrix. EDIT Based on Tordin's answer, it sems like I have to modify my code like so: var elements = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("INSTANCE0", 0, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1), new InputElement("INSTANCE1", 1, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1), new InputElement("INSTANCE2", 2, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1), new InputElement("INSTANCE3", 3, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerInstanceData, 1), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }; and in the shader: struct VIn { float4 position: POSITION; float4 instance0: INSTANCE0; float4 instance1: INSTANCE1; float4 instance2: INSTANCE2; float4 instance3: INSTANCE3; float4 color: COLOR; }; VOut VShader(VIn input) { VOut output; matrix world = { input.instance0, input.instance1, input.instance2, input.instance3 }; output.position = mul(input.position, world); output.position = mul(output.position, View); output.position = mul(output.position, Projection); output.color = input.color; return output; } However I still get an exception.

    Read the article

  • C++ OpenGL wireframe cube rendering blank

    - by caleb.breckon
    I'm just trying to draw a bunch of lines that make up a "cube". I can't for the life of me figure out why this is producing a black screen. The debugger does not break at any point. I'm sure it's a problem with my pointers, as I'm only decent at them in regular c++ and in OpenGL it gets even worse. const char* vertexSource = "#version 150\n" "in vec3 position;" "void main() {" " gl_Position = vec4(position, 1.0);" "}"; const char* fragmentSource = "#version 150\n" "out vec4 outColor;" "void main() {" " outColor = vec4(1.0, 1.0, 1.0, 1.0);" "}"; int main() { initializeGLFW(); // Initialize GLEW glewExperimental = GL_TRUE; glewInit(); // Create Vertex Array Object GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // Create a Vertex Buffer Object and copy the vertex data to it GLuint vbo; glGenBuffers( 1, &vbo ); float vertices[] = { 1.0f, 1.0f, 1.0f, // Vertex 0 (X, Y, Z) -1.0f, 1.0f, 1.0f, // Vertex 1 (X, Y, Z) -1.0f, -1.0f, 1.0f, // Vertex 2 (X, Y, Z) 1.0f, -1.0f, 1.0f, // Vertex 3 (X, Y, Z) 1.0f, 1.0f, -1.0f, // Vertex 4 (X, Y, Z) -1.0f, 1.0f, -1.0f, // Vertex 5 (X, Y, Z) -1.0f, -1.0f, -1.0f, // Vertex 6 (X, Y, Z) 1.0f, -1.0f, -1.0f // Vertex 7 (X, Y, Z) }; GLuint indices[] = { 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 }; glBindBuffer( GL_ARRAY_BUFFER, vbo ); glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); //glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vbo); //glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( indices ), indices, GL_STATIC_DRAW ); // Create and compile the vertex shader GLuint vertexShader = glCreateShader( GL_VERTEX_SHADER ); glShaderSource( vertexShader, 1, &vertexSource, NULL ); glCompileShader( vertexShader ); // Create and compile the fragment shader GLuint fragmentShader = glCreateShader( GL_FRAGMENT_SHADER ); glShaderSource( fragmentShader, 1, &fragmentSource, NULL ); glCompileShader( fragmentShader ); // Link the vertex and fragment shader into a shader program GLuint shaderProgram = glCreateProgram(); glAttachShader( shaderProgram, vertexShader ); glAttachShader( shaderProgram, fragmentShader ); glBindFragDataLocation( shaderProgram, 0, "outColor" ); glLinkProgram (shaderProgram); glUseProgram( shaderProgram); // Specify the layout of the vertex data GLint posAttrib = glGetAttribLocation( shaderProgram, "position" ); glEnableVertexAttribArray( posAttrib ); glVertexAttribPointer( posAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0 ); // Main loop while(glfwGetWindowParam(GLFW_OPENED)) { // Clear the screen to black glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); glClear( GL_COLOR_BUFFER_BIT ); // Draw lines from 2 vertices glDrawElements(GL_LINES, sizeof(indices), GL_UNSIGNED_INT, indices ); // Swap buffers glfwSwapBuffers(); } // Clean up glDeleteProgram( shaderProgram ); glDeleteShader( fragmentShader ); glDeleteShader( vertexShader ); //glDeleteBuffers( 1, &ebo ); glDeleteBuffers( 1, &vbo ); glDeleteVertexArrays( 1, &vao ); glfwTerminate(); exit( EXIT_SUCCESS ); }

    Read the article

  • DirectX particle system. ConstantBuffer

    - by Liuka
    I'm new in DirectX and I'm making a 2D game. I want to use a particle system to simulate a 3D starfield, so each star has to set its own constant buffer for the vertexshader es. to set it's world matrix. So if i have 500 stars (that move every frame) i need to call 500 times VSsetconstantbuffer, and map/unmap each buffer. with 500 stars i have an average of 220 fps and that's quite good. My bottelneck is Vs/PsSetconstantbuffer. If i dont call this function i have 400 fps(obliviously nothing is display, since i dont set the position of the stars). So is there a method to speed up the render of the particle system?? Ps. I'm using intel integrate graphic (hd 2000-3000). with a nvidia (or amd) gpu will i have the same bottleneck?? If, for example, i dont call setshaderresource i have 10-20 fps more (for 500 objcets), that is not 180.Why does SetConstantBuffer take so long?? LPVOID VSdataPtr = VSmappedResource.pData; memcpy(VSdataPtr, VSdata, CszVSdata); context->Unmap(VertexBuffer, 0); result = context->Map(PixelBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &PSmappedResource); if (FAILED(result)) { outputResult.OutputErrorMessage(TITLE, L"Cannot map the PixelBuffer", &result, OUTPUT_ERROR_FILE); return; } LPVOID PSdataPtr = PSmappedResource.pData; memcpy(PSdataPtr, PSdata, CszPSdata); context->Unmap(PixelBuffer, 0); context->VSSetConstantBuffers(0, 1, &VertexBuffer); context->PSSetConstantBuffers(0, 1, &PixelBuffer); this update and set the buffer. It's part of the render method of a sprite class that contains a the vertex buffer and the texture to apply to the quads(it's a 2d game) too. I have an array of 500 stars (sprite setup with a star texture). Every frame: clear back buffer; draw the array of stars; present the backbuffer; draw also call the function update( which calculate the position of the sprite on screen based on a "camera class") Ok, create a vertex buffer with the vertices of each quads(stars) seems to be good, since the stars don't change their "virtual" position; so.... In a particle system (where particles move) it's better to have all the object in only one vertices array, rather then an array of different sprite/object in order to update all the vertices' position with a single setbuffer call. In this case i have to use a dynamic vertex buffer with the vertices positions like this: verticesForQuad={{ XMFLOAT3((float)halfDImensions.x-1+pos.x, (float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(1.0f, 0.0f) }, { XMFLOAT3((float)halfDImensions.x-1+pos.x, -(float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(1.0f, 1.0f) }, { XMFLOAT3(-(float)halfDImensions.x-1+pos.x, (float)halfDImensions.y-1.pos.y, 1.0f), XMFLOAT2(0.0f, 0.0f) }, { XMFLOAT3(-(float)halfDImensions.x-1.pos.x, -(float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(0.0f, 1.0f) }, ....other quads} where halfDimensions is the halfsize in pixel of a texture and pos the virtual position of a star. than create an array of verticesForQuad and create the vertex buffer ZeroMemory(&vertexDesc, sizeof(vertexDesc)); vertexDesc.Usage = D3D11_USAGE_DEFAULT; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof(VertexType)* 4*numStars; ZeroMemory(&resourceData, sizeof(resourceData)); resourceData.pSysMem = verticesForQuad; result = device->CreateBuffer(&vertexDesc, &resourceData, &CvertexBuffer); and call each frame Context->IASetVertexBuffers(0, 1, &CvertexBuffer, &stride, &offset); But if i want to add and remove obj i have to recreate the buffer each time, havent i?? There is a faster way? I think i can create a vertex buffer with a max size (es. 10000 objs) and when i update it set only the 250 position (for 250 onjs for example) and pass this number as the vertexCount to the draw function (numObjs*4), or i'm worng

    Read the article

  • Multidimensional array with unequal second dimension size using malloc()

    - by user288422
    Hello, I am playing around with multidimensional array of unequal second dimension size. Lets assume that I need the following data structure: [&ptr0]-[0][1][2][3][4][5][6][7][8][9] [&ptr1]-[0][1][2] [&ptr2]-[0][1][2][3][4] int main() { int *a[3]; int *b; int i; a[0] = (int *)malloc(10 * sizeof(int)); a[1] = (int *)malloc(2 * sizeof(int)); a[2] = (int *)malloc(4 * sizeof(int)); for(i=0; i<10; i++) a[0][i]=i; for(i=0; i<2; i++) a[1][i]=i; for(i=0; i<4; i++) a[2][i]=i; } I did some tests and it seems like I can store a value at a[1][3]. Does it mean that rows in my array are of equal size 10?

    Read the article

  • How do you dynamically allocate a contiguous 3D array in C?

    - by Derek
    In C, I want to loop through an array in this order for(int z = 0; z < NZ; z++) for(int x = 0; x < NX; x++) for(int y = 0; y < NY; y++) 3Darray[x][y][z] = 100; How do I create this array in such a way that 3Darray[0][1][0] comes right before 3Darray[0][2][0] in memory? I can get an initialization to work that gives me "z-major" ordering, but I really want a y-major ordering for this 3d array This is the code I have been trying to use: char *space; char ***Arr3D; int y, z; ptrdiff_t diff; space = malloc(X_DIM * Y_DIM * Z_DIM * sizeof(char)) Arr3D = malloc(Z_DIM * sizeof(char **)); for (z = 0; z < Z_DIM; z++) { Arr3D[z] = malloc(Y_DIM * sizeof(char *)); for (y = 0; y < Y_DIM; y++) { Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM); } }

    Read the article

  • Why does RunDLL32 process exit early on Windows 7?

    - by Vicky
    On Windows XP and Vista, I can run this code: STARTUPINFO si; PROCESS_INFORMATION pi; BOOL bResult = FALSE; ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&si, sizeof(si)); si.cb = sizeof(STARTUPINFO); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_SHOW; bResult = CreateProcess(NULL, "rundll32.exe shell32.dll,Control_RunDLL modem.cpl", NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi); if (bResult) { WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } and it operates as I would expect, i.e. the WaitForSingleObject does not return until the Modem Control Panel window has been closed by the user. On Windows 7, the same code, WaitForSingleObject returns straight away (with a return code of 0 indicating that the object signalled the requested state). Similarly, if I take it to the command line, on XP and Vista I can run start /wait rundll32.exe shell32.dll,Control_RunDLL modem.cpl and it does not return control to the command prompt until the Control Panel window is closed, but on Windows 7 it returns immediately. Is this a change in RunDll32? I know MS made some changes to RunDll32 in Windows 7 for UAC, and it looks from these experiments as though one of those changes might have involved spawning an additional process to display the window, and allowing the originating process to exit. The only thing that makes me think this might not be the case is that using a process explorer that shows the creation and destruction of processes, I do not see anything additional being created beyond the called rundll32 process itself. Any other way I can solve this? I just don't want the function to return until the control panel window is closed.

    Read the article

  • C malloc assertion help

    - by Chris
    I am implementing a divide and conquer polynomial algorithm so i can bench it against an opencl implementation, but i can't seem to get malloc to work. When I run the program it allocates a bunch of stuff, checks some things, then sends the size/2 to the algorithm. Then when I hit the malloc line again it spits out this: malloc.c:3096: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)-bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) = (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)-size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed. Aborted The line in question is: int *out, .....other vars....; out = (int *)malloc(sizeof(int) * size * 2); I have checked size with fprintf and it is a positive int (usually 50 at that point). I have tried calling malloc with a plain number as well and i still get the error. I'm just stumped at what's going on, and nothing from google that I have found so far has been too helpful. Any ideas what's going on? I'm trying to figure out how to compile a newer GCC in case it's a compiler error, but i really doubt it.

    Read the article

  • Core Audio on iPhone - any way to change the microphone gain (either for speakerphone mic or headpho

    - by Halle
    After much searching the answer seems to be no, but I thought I'd ask here before giving up. For a project I'm working on that includes recording sound, the input levels sound a little quiet both when the route is external mic + speaker and when it's headphone mic + headphones. Does anyone know definitively whether it is possible to programmatically change mic gain levels on the iPhone in any part of Core Audio? If not, is it possible that I'm not really in "speakerphone" mode (with the external mic at least) but only think I am? Here is my audio session init code: OSStatus error = AudioSessionInitialize(NULL, NULL, audioQueueHelperInterruptionListener, r); [...some error checking of the OSStatus...] UInt32 category = kAudioSessionCategory_PlayAndRecord; // need to play out the speaker at full volume too so it is necessary to change default route below error = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category); if (error) printf("couldn't set audio category!"); UInt32 doChangeDefaultRoute = 1; error = AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof (doChangeDefaultRoute), &doChangeDefaultRoute); if (error) printf("couldn't change default route!"); error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, audioQueueHelperPropListener, r); if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", (int)error); UInt32 inputAvailable = 0; UInt32 size = sizeof(inputAvailable); error = AudioSessionGetProperty(kAudioSessionProperty_AudioInputAvailable, &size, &inputAvailable); if (error) printf("ERROR GETTING INPUT AVAILABILITY! %d\n", (int)error); error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioInputAvailable, audioQueueHelperPropListener, r); if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", (int)error); error = AudioSessionSetActive(true); if (error) printf("AudioSessionSetActive (true) failed"); Thanks very much for any pointers.

    Read the article

  • malloc works, cudaHostAlloc segfaults?

    - by Mikhail
    I am new to CUDA and I want to use cudaHostAlloc. I was able to isolate my problem to this following code. Using malloc for host allocation works, using cudaHostAlloc results in a segfault, possibly because the area allocated is invalid? When I dump the pointer in both cases it is not null, so cudaHostAlloc returns something... works in_h = (int*) malloc(length*sizeof(int)); //works for (int i = 0;i<length;i++) in_h[i]=2; doesn't work cudaHostAlloc((void**)&in_h,length*sizeof(int),cudaHostAllocDefault); for (int i = 0;i<length;i++) in_h[i]=2; //segfaults Standalone Code #include <stdio.h> void checkDevice() { cudaDeviceProp info; int deviceName; cudaGetDevice(&deviceName); cudaGetDeviceProperties(&info,deviceName); if (!info.deviceOverlap) { printf("Compute device can't use streams and should be discared."); exit(EXIT_FAILURE); } } int main() { checkDevice(); int *in_h; const int length = 10000; cudaHostAlloc((void**)&in_h,length*sizeof(int),cudaHostAllocDefault); printf("segfault comming %d\n",in_h); for (int i = 0;i<length;i++) { in_h[i]=2; } free(in_h); return EXIT_SUCCESS; } ~ Invocation [id129]$ nvcc fun.cu [id129]$ ./a.out segfault comming 327641824 Segmentation fault (core dumped) Details Program is run in interactive mode on a cluster. I was told that an invocation of the program from the compute node pushes it to the cluster. Have not had any trouble with other home made toy cuda codes.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >