Search Results

Search found 185 results on 8 pages for 'strcpy'.

Page 1/8 | 1 2 3 4 5 6 7 8  | Next Page >

  • strcpy v/s memcpy

    - by Sachin Chourasiya
    What is the difference between memcpy() and strcpy()? I tried to find it with the help of a program but both are giving the same output. int main() { char s[5]={'s','a','\0','c','h'}; char p[5]; char t[5]; strcpy(p,s); memcpy(t,s,5); printf("sachin p is [%s], t is [%s]",p,t); return 0; } Output sachin p is [sa], t is [sa]

    Read the article

  • C++ Why isn't call by reference needed for strcpy()

    - by Ribbs
    I have a homework assignment with a number of questions. One is asking why the strcpy() function doesn't need the call by reference operator for CStrings. I've looked through the book numerous times and I can't, for the life of me, find the answer. Can anyone help explain this to me? It is an array of sorts so I would think you would need the call by reference.

    Read the article

  • Strcpy() corrupts the copied string in Solaris but not Linux

    - by strictlyrude27
    Hi all, I'm writing a C code for a class. This class requires that our code compile and run on the school server, which is a sparc solaris machine. I'm running Linux x64. I have this line to parse (THIS IS NOT ACTUAL CODE BUT IS INPUT TO MY PROGRAM): while ( cond1 ){ I need to capture the "while" and the "cond1" into separate strings. I've been using strtok() to do this. In Linux, the following lines: char *cond = NULL; cond = (char *)malloc(sizeof(char)); memset(cond, 0, sizeof(char)); strcpy(cond, strtok(NULL, ": \t\(){")); //already got the "while" out of the line will correctly capture the string "cond1".Running this on the solaris machine, however, gives me the string "cone1". Note that in plenty of other cases within my program, strings are being copied correctly. (For instance, the "while") was captured correctly. Does anyone know what is going on here?

    Read the article

  • 'strcpy' error and warning

    - by Leejo
    I'm getting a 'strcpy' error and warning for the following lines: _tcscpy(strCommandLine,_T("MyProgram.exe /param1")); _tcscpy(strApplicationName,_T("MyProgram.exe")); Not sure why I'm getting a 'strcpy' error or warning since I'm not using 'strcpy'. The only lines related to this is: LPCTSTR strApplicationName; LPTSTR strCommandLine; _tcscpy(strCommandLine,_T("MyProgram.exe /param1")); //warning is on this line _tcscpy(strApplicationName,_T("MyProgram.exe")); //error is on this line The output is: 1c:\documents and settings\X.X\my documents\sandbox\sample.cpp(52) : warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 1 c:\program files\microsoft visual studio 8\vc\include\string.h(74) : see declaration of 'strcpy' 1c:\documents and settings\X.X\my documents\sandbox\sample.cpp(53) : error C2664: 'strcpy' : cannot convert parameter 1 from 'LPCTSTR' to 'char *' 1 Conversion loses qualifiers Any ideas on what this could means? These are my headers: iostream windows.h stdio.h tchar.h winnt.h

    Read the article

  • snprintf vs strcpy(etc) in c

    - by monkeyking
    For doing string concatenation I've been doing basic strcpy,strncpy of char* buffers. Then I learned about the snprintf and friends. Should I stick with my strcpy,strcpy + \0 terminiation. Or should I just use snprintf in the future? thanks

    Read the article

  • Segmentation fault in strcpy

    - by Alien01
    consider the program below char str[5]; strcpy(str,"Hello12345678"); printf("%s",str); When run this program gives segmentation fault. But when strcpy is replaced with following, program runs fine. strcpy(str,"Hello1234567"); So question is it should crash when trying to copy to str any other string of more than 5 chars length. So why it is not crashing for "Hello1234567" and only crashing for "Hello12345678" ie of string with length 13 or more than 13. This program was run on 32 bit machine .

    Read the article

  • wordexp followed by strcpy = EXC_BAD_ACCESS + sharedlibrary apply-load-rules-all

    - by fyngyrz
    The implication is a memory problem. I have static allocations for these: char akdir[400]; char homedir[400]; This crashes on the first strcpy(): void setuplibfoo() { long ii; double x; wordexp_t result; // This obtains the user's home directory // -------------------------------------- homedir[0]=0; // in case wordexp fails switch (wordexp("~/",&result,0)) { case 0: // Successful. We'll fall into deallocate when done. { strcpy(homedir,result.we_wordv[0]); // <<--- CRASH! strcpy(akdir,homedir); strcat(akdir,"ak-plugins/"); vs_status(akdir); } case WRDE_NOSPACE: // If the error was WRDE_NOSPACE, then { // perhaps part of the result was allocated. wordfree (&result); } default: // all other errors do not require deallocation { break; } } ...additional code clipped.. doesn't get there on crash. This is in a shared library I've written that is linked to my application, also something I've written. In this case, it doesn't get very far, although if it starts, it's fine. ...I've read the wordexp docs several times; they say they allocate new objects, so you just set up that type and call them with the address. The switch error model is right from the wordexp docs: http://www.gnu.org/s/libc/manual/html_mono/libc.html#Wordexp-Example It doesn't always crash. Just sometimes, and just under 10.6. Never under 10.5 I'm building debug mode with XCode 3.1.1, under OSX 10.5.8 it seems to run ok, I've not seen a crash -- under 10.6, it crashes... sometimes. But always with that same exception, and always in the same place. The Google has it that this actually means, somehow, that it's too soon to allocate memory. But all the instances I could find were memory errors on the part of the programmer. Overruns, etc. And I can't find any docs on when it IS safe to allocate memory. Now, the path that expands there is nowhere near 400 characters. it's this (it it completes): /Users/flake/ak-plugins/ and this: /Users/flake/ ...if it doesn't. the strcpy... copies 2nd param to first. Theirs to mine. And it works! under 10.5. :/ So is wordexp broke? Is 10.6 broke? Am I cRaZy? Here's the debugger output: 0x00013446 <+0049> call 0xc98da <dyld_stub_wordexp> 0x0001344b <+0054> test %eax,%eax 0x0001344d <+0056> je 0x13454 <setuplibfoo+63> 0x0001344f <+0058> jmp 0x134da <setuplibfoo+197> 0x00013454 <+0063> mov -0x1c(%ebp),%eax 0x00013457 <+0066> mov (%eax),%eax 0x00013459 <+0068> mov %eax,0x4(%esp) 0x0001345d <+0072> lea 0xb6cc2(%ebx),%eax 0x00013463 <+0078> mov (%eax),%eax 0x00013465 <+0080> mov %eax,(%esp) 0x00013468 <+0083> call 0xc9898 <dyld_stub_strcpy> 0x0001346d <+0088> lea 0xb6cc2(%ebx),%eax <<--CRASH!

    Read the article

  • whats wrong with strcpy()

    - by blacktooth
    What is wrong with strcpy() in this code? void process_filedata(char *filename) { void* content; const char * buffer; char * temp; char * row; char * col; int lsize,buflen,tmp,num_scan; //num_scan - number of characters scanned int m=0,p=0,d=0,j=0; //m - machine, p - phase, d- delimiter, j - job FILE *file_pointer = fopen("machinetimesnew.csv","r"); if(file_pointer == NULL) { error_flag = print_error("Error opening file"); if(error_flag) exit(1); } fseek(file_pointer, 0 ,SEEK_END); lsize = ftell(file_pointer); buflen = lsize; rewind(file_pointer); // content = (char*) malloc(sizeof(char)*lsize); fread(content,1,lsize,file_pointer); buffer = (const char*) content; strcpy(temp,buffer); row = strtok(temp,"\n"); ............... ............... I am getting a segmentation fault..

    Read the article

  • C++ strcpy(Struct.Property, "VALUE") Use in C#?

    - by gtas
    Hi all, i created a Wrapper for a C++ dll. While reading the documentation i reached to a point using this function strcpy(StructName.strPropGetter, "A STRING"); I'm not kinda C++ guy, i can't figure how to transfer this code in C#. My wrapper gave me this property without a setter. Any light would be nice. Thank you

    Read the article

  • I have a Segmentation fault (core dumped) when using strcpy, malloc, and struct

    - by malsh002
    Okay, when I run this code, I have a segmentation fault #include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX 64 struct example { char *name; }; int main() { struct example *s = malloc (MAX); strcpy(s->name ,"Hello World!!"); return !printf("%s\n", s->name); } the terminal output: alshamlan@alshamlan-VGN-CR520E:/tmp/interview$ make q1 cc -Wall -g q1.c -o q1 alshamlan@alshamlan-VGN-CR520E:/tmp/interview$ ./q1 Segmentation fault (core dumped) alshamlan@alshamlan-VGN-CR520E:/tmp/interview$ gedit q1.c Can someone explain what's going on? thanks.

    Read the article

  • Strcpy and malloc issues

    - by mrblippy
    Hi, i am having trouble getting a method relating to a linked list working, i get the errors: assignment makes pointer from integer without a cast and passing argument 1 of âstrcpyâ makes pointer from integer without a cast. i have tried to include all the relevant code, but let me know if you need more info. thanks. struct unit { char code[5]; char *name; node_ptr students; }; typedef struct node *node_ptr; struct node { int student_id; char *studentname; node_ptr next; }; void enrol_student(struct unit u[], int n) { int i, p; int student_id = 0; char code_to_enrol[7]; char buffer[100]; node_ptr studentslist; scanf("%s\n", code_to_enrol); for(i=0; i <= n; i++) { studentslist = u[i].students; if(strcmp(u[i].code ,code_to_enrol)<=0) { scanf("enter student details %d %s\n", &studentID, buffer); p = (char *) malloc (strlen(buffer)+1); strcpy(p, buffer); insert_in_order(student_id, buffer, studentslist); } } } void insert_in_order(int n, char *i, node_ptr list) { node_ptr before = list; node_ptr students = (node_ptr) malloc(sizeof(struct node)); students->ID = n; students->name = *i; while(before->next && (before->next->ID < n)) { before = before->next; } students->next = before->next; before->next = students; }

    Read the article

  • Copy results of strtok to 2 strings in C

    - by Mr. Man
    Ok, so I have the code char *token; char *delimiter = " "; token = strtok(command, delimiter); strcpy(command, token); token = strtok(NULL, delimiter); strcpy(arguments, token); and it gives me EXC_BAD_ACCESS when i run it, and yes, command and arguments are already defined.

    Read the article

  • dynamic char array sizing

    - by droseman
    Hello, In my application, I have a char array defined which can take one of three options: "okay", "high", "low" which are then sent down a serial port to a remote device. I currently have the array sized to take the 4 character words plus carriage return and line feed, but when I have to send "low" I get a null character in the strings, which I am concerned would confuse the host terminal. array definition char mod1_status_char[6] = {'0','0','0','0','0','0'}; char mod2_status_char[6] = {'0','0','0','0','0','0'}; char mod3_status_char[6] = {'0','0','0','0','0','0'}; sample of switch case statement: void DCOKStatus(uint8_t *ptr_status) { uint8_t status = *ptr_status; switch (status) { case 0x00: strcpy(mod1_status_char, "okay"); strcpy(mod2_status_char, "okay"); strcpy(mod3_status_char, "okay"); break; case 0x10: strcpy(mod1_status_char, "okay"); strcpy(mod2_status_char, "okay"); strcpy(mod3_status_char, "low"); break; } This is the struct which makes the message string to send strcpy(MsgStatus_on.descriptor_msg, "$psu_"); MsgStatus_on.address01 = hex_addr[0]; MsgStatus_on.address02 = hex_addr[1]; MsgStatus_on.space01 = 0x20; strcpy(MsgStatus_on.cmdmsg01, "op_en op1_"); strcpy(MsgStatus_on.statusmsg01, mod1_status_char); MsgStatus_on.space02 = 0x20; strcpy(MsgStatus_on.cmdmsg02, "op2_"); strcpy(MsgStatus_on.statusmsg02, mod2_status_char); MsgStatus_on.space03 = 0x20; strcpy(MsgStatus_on.cmdmsg03, "op3_"); strcpy(MsgStatus_on.statusmsg03, mod3_status_char); MsgStatus_on.CR = 0x0D; MsgStatus_on.LF = 0x0A; and this sends the message void USARTWrite(char *object, uint32_t size) { GPIO_SetBits(GPIOB, GPIO_Pin_1); char *byte; for (byte = object; size--; ++byte) { USART_SendData(USART1,*byte); } Would anyone be able to suggest a good approach to dynamically size the array to one character shorter when I need to send "low"? Thanks

    Read the article

  • Espeak SAPI/dll usage on Windows ?

    - by Quandary
    Question: I am trying to use the espeak text-to-speech engine. So for I got it working wounderfully on linux (code below). Now I wanted to port this basic program to windows, too, but it's nearly impossible... Part of the problem is that the windows dll only allows for AUDIO_OUTPUT_SYNCHRONOUS, which means it requires a callback, but I can't figure out how to play the audio from the callback... First it crashed, then I realized, I need a callback function, now I get the data in the callback function, but I don't know how to play it... as it is neither a wav file nor plays automatically as on Linux. The sourceforge site is rather useless, because it basically says use the SAPI version, but then there is no example on how to use the sapi espeak dll... Anyway, here's my code, can anybody help? #ifdef __cplusplus #include <cstdio> #include <cstdlib> #include <cstring> else #include <stdio.h> #include <stdlib.h> #include <string.h> endif include include //#include "speak_lib.h" include "espeak/speak_lib.h" // libespeak-dev: /usr/include/espeak/speak_lib.h // apt-get install libespeak-dev // apt-get install libportaudio-dev // g++ -o mine mine.cpp -lespeak // g++ -o mine mine.cpp -I/usr/include/espeak/ -lespeak // gcc -o mine mine.cpp -I/usr/include/espeak/ -lespeak char voicename[40]; int samplerate; int quiet = 0; static char genders[4] = {' ','M','F',' '}; //const char *data_path = "/usr/share/"; // /usr/share/espeak-data/ const char *data_path = NULL; // use default path for espeak-data int strrcmp(const char *s, const char *sub) { int slen = strlen(s); int sublen = strlen(sub); return memcmp(s + slen - sublen, sub, sublen); } char * strrcpy(char *dest, const char *source) { // Pre assertions assert(dest != NULL); assert(source != NULL); assert(dest != source); // tk: parentheses while((*dest++ = *source++)) ; return(--dest); } const char* GetLanguageVoiceName(const char* pszShortSign) { #define LANGUAGE_LENGTH 30 static char szReturnValue[LANGUAGE_LENGTH] ; memset(szReturnValue, 0, LANGUAGE_LENGTH); for (int i = 0; pszShortSign[i] != '\0'; ++i) szReturnValue[i] = (char) tolower(pszShortSign[i]); const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { if( !strrcmp( v->languages, szReturnValue) ) { strcpy(szReturnValue, v->name); return szReturnValue; } } // End for strcpy(szReturnValue, "default"); return szReturnValue; } // End function getvoicename void ListVoices() { const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { printf("Shortsign: %s\n", v->languages); printf("age: %d\n", v->age); printf("gender: %c\n", genders[v->gender]); printf("name: %s\n", v->name); printf("\n\n"); } // End for } // End function getvoicename int main() { printf("Hello World!\n"); const char* szVersionInfo = espeak_Info(NULL); printf("Espeak version: %s\n", szVersionInfo); samplerate = espeak_Initialize(AUDIO_OUTPUT_PLAYBACK,0,data_path,0); strcpy(voicename, "default"); // espeak --voices strcpy(voicename, "german"); strcpy(voicename, GetLanguageVoiceName("DE")); if(espeak_SetVoiceByName(voicename) != EE_OK) { printf("Espeak setvoice error...\n"); } static char word[200] = "Hello World" ; strcpy(word, "TV-fäns aufgepasst, es ist 20 Uhr 15. Zeit für Rambo 3"); strcpy(word, "Unnamed Player wurde zum Opfer von GSG9"); int speed = 220; int volume = 500; // volume in range 0-100 0=silence int pitch = 50; // base pitch, range 0-100. 50=normal // espeak.cpp 625 espeak_SetParameter(espeakRATE, speed, 0); espeak_SetParameter(espeakVOLUME,volume,0); espeak_SetParameter(espeakPITCH,pitch,0); // espeakRANGE: pitch range, range 0-100. 0-monotone, 50=normal // espeakPUNCTUATION: which punctuation characters to announce: // value in espeak_PUNCT_TYPE (none, all, some), espeak_VOICE *voice_spec = espeak_GetCurrentVoice(); voice_spec->gender=2; // 0=none 1=male, 2=female, //voice_spec->age = age; espeak_SetVoiceByProperties(voice_spec); espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL); espeak_Synchronize(); strcpy(voicename, GetLanguageVoiceName("EN")); espeak_SetVoiceByName(voicename); strcpy(word, "Geany was fragged by GSG9 Googlebot"); strcpy(word, "Googlebot"); espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL); espeak_Synchronize(); espeak_Terminate(); printf("Espeak terminated\n"); return EXIT_SUCCESS; } /* if(espeak_SetVoiceByName(voicename) != EE_OK) { memset(&voice_select,0,sizeof(voice_select)); voice_select.languages = voicename; if(espeak_SetVoiceByProperties(&voice_select) != EE_OK) { fprintf(stderr,"%svoice '%s'\n",err_load,voicename); exit(2); } } */ The above code is for Linux. The below code is about as far as I got on Vista x64 (32 bit emu): #ifdef __cplusplus #include <cstdio> #include <cstdlib> #include <cstring> else #include <stdio.h> #include <stdlib.h> #include <string.h> endif include include include "speak_lib.h" //#include "espeak/speak_lib.h" // libespeak-dev: /usr/include/espeak/speak_lib.h // apt-get install libespeak-dev // apt-get install libportaudio-dev // g++ -o mine mine.cpp -lespeak // g++ -o mine mine.cpp -I/usr/include/espeak/ -lespeak // gcc -o mine mine.cpp -I/usr/include/espeak/ -lespeak char voicename[40]; int iSampleRate; int quiet = 0; static char genders[4] = {' ','M','F',' '}; //const char *data_path = "/usr/share/"; // /usr/share/espeak-data/ //const char *data_path = NULL; // use default path for espeak-data const char *data_path = "C:\Users\Username\Desktop\espeak-1.43-source\espeak-1.43-source\"; int strrcmp(const char *s, const char *sub) { int slen = strlen(s); int sublen = strlen(sub); return memcmp(s + slen - sublen, sub, sublen); } char * strrcpy(char *dest, const char *source) { // Pre assertions assert(dest != NULL); assert(source != NULL); assert(dest != source); // tk: parentheses while((*dest++ = *source++)) ; return(--dest); } const char* GetLanguageVoiceName(const char* pszShortSign) { #define LANGUAGE_LENGTH 30 static char szReturnValue[LANGUAGE_LENGTH] ; memset(szReturnValue, 0, LANGUAGE_LENGTH); for (int i = 0; pszShortSign[i] != '\0'; ++i) szReturnValue[i] = (char) tolower(pszShortSign[i]); const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { if( !strrcmp( v->languages, szReturnValue) ) { strcpy(szReturnValue, v->name); return szReturnValue; } } // End for strcpy(szReturnValue, "default"); return szReturnValue; } // End function getvoicename void ListVoices() { const espeak_VOICE **voices; espeak_VOICE voice_select; voices = espeak_ListVoices(NULL); const espeak_VOICE *v; for(int ix=0; (v = voices[ix]) != NULL; ix++) { printf("Shortsign: %s\n", v->languages); printf("age: %d\n", v->age); printf("gender: %c\n", genders[v->gender]); printf("name: %s\n", v->name); printf("\n\n"); } // End for } // End function getvoicename /* Callback from espeak. Directly speaks using AudioTrack. */ define LOGI(x) printf("%s\n", x) static int AndroidEspeakDirectSpeechCallback(short *wav, int numsamples, espeak_EVENT *events) { char buf[100]; sprintf(buf, "AndroidEspeakDirectSpeechCallback: %d samples", numsamples); LOGI(buf); if (wav == NULL) { LOGI("Null: speech has completed"); } if (numsamples > 0) { //audout->write(wav, sizeof(short) * numsamples); sprintf(buf, "AudioTrack wrote: %d bytes", sizeof(short) * numsamples); LOGI(buf); } return 0; // continue synthesis (1 is to abort) } static int AndroidEspeakSynthToFileCallback(short *wav, int numsamples,espeak_EVENT *events) { char buf[100]; sprintf(buf, "AndroidEspeakSynthToFileCallback: %d samples", numsamples); LOGI(buf); if (wav == NULL) { LOGI("Null: speech has completed"); } // The user data should contain the file pointer of the file to write to //void* user_data = events->user_data; FILE* user_data = fopen ( "myfile1.wav" , "ab" ); FILE* fp = static_cast<FILE *>(user_data); // Write all of the samples fwrite(wav, sizeof(short), numsamples, fp); return 0; // continue synthesis (1 is to abort) } int main() { printf("Hello World!\n"); const char* szVersionInfo = espeak_Info(NULL); printf("Espeak version: %s\n", szVersionInfo); iSampleRate = espeak_Initialize(AUDIO_OUTPUT_SYNCHRONOUS, 4096, data_path, 0); if (iSampleRate <= 0) { printf("Unable to initialize espeak"); return EXIT_FAILURE; } //samplerate = espeak_Initialize(AUDIO_OUTPUT_PLAYBACK,0,data_path,0); //ListVoices(); strcpy(voicename, "default"); // espeak --voices //strcpy(voicename, "german"); //strcpy(voicename, GetLanguageVoiceName("DE")); if(espeak_SetVoiceByName(voicename) != EE_OK) { printf("Espeak setvoice error...\n"); } static char word[200] = "Hello World" ; strcpy(word, "TV-fäns aufgepasst, es ist 20 Uhr 15. Zeit für Rambo 3"); strcpy(word, "Unnamed Player wurde zum Opfer von GSG9"); int speed = 220; int volume = 500; // volume in range 0-100 0=silence int pitch = 50; // base pitch, range 0-100. 50=normal // espeak.cpp 625 espeak_SetParameter(espeakRATE, speed, 0); espeak_SetParameter(espeakVOLUME,volume,0); espeak_SetParameter(espeakPITCH,pitch,0); // espeakRANGE: pitch range, range 0-100. 0-monotone, 50=normal // espeakPUNCTUATION: which punctuation characters to announce: // value in espeak_PUNCT_TYPE (none, all, some), //espeak_VOICE *voice_spec = espeak_GetCurrentVoice(); //voice_spec->gender=2; // 0=none 1=male, 2=female, //voice_spec->age = age; //espeak_SetVoiceByProperties(voice_spec); //espeak_SetSynthCallback(AndroidEspeakDirectSpeechCallback); espeak_SetSynthCallback(AndroidEspeakSynthToFileCallback); unsigned int unique_identifier; espeak_ERROR err = espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, &unique_identifier, NULL); err = espeak_Synchronize(); /* strcpy(voicename, GetLanguageVoiceName("EN")); espeak_SetVoiceByName(voicename); strcpy(word, "Geany was fragged by GSG9 Googlebot"); strcpy(word, "Googlebot"); espeak_Synth( (char*) word, strlen(word)+1, 0, POS_CHARACTER, 0, espeakCHARS_AUTO, NULL, NULL); espeak_Synchronize(); */ // espeak_Cancel(); espeak_Terminate(); printf("Espeak terminated\n"); system("pause"); return EXIT_SUCCESS; }

    Read the article

  • Grading an algorithm: Readability vs. Compactness

    - by amiregelz
    Consider the following question in a test \ interview: Implement the strcpy() function in C: void strcpy(char *destination, char *source); The strcpy function copies the C string pointed by source into the array pointed by destination, including the terminating null character. Assume that the size of the array pointed by destination is long enough to contain the same C string as source, and does not overlap in memory with source. Say you were the tester, how would you grade the following answers to this question? 1) void strcpy(char *destination, char *source) { while (*source != '\0') { *destination = *source; source++; destionation++; } *destionation = *source; } 2) void strcpy(char *destination, char *source) { while (*(destination++) = *(source++)) ; } The first implementation is straightforward - it is readable and programmer-friendly. The second implementation is shorter (one line of code) but less programmer-friendly; it's not so easy to understand the way this code is working, and if you're not familiar with the priorities in this code then it's a problem. I'm wondering if the first answer would show more complexity and more advanced thinking, in the tester's eyes, even though both algorithms behave the same, and although code readability is considered to be more important than code compactness. It seems to me that since making an algorithm this compact is more difficult to implement, it will show a higher level of thinking as an answer in a test. However, it is also possible that a tester would consider the first answer not good because it's not readable. I would also like to mention that this is not specific to this example, but general for code readability vs. compactness when implementing an algorithm, specifically in tests \ interviews.

    Read the article

  • Problem with C function of type char pointer, can someone explain?

    - by JJ
    Find the errors from following C function : char* f(int i) { int i; char buffer[20]; switch ( i ) { 1: strcpy( buffer, "string1"); 2: strcpy( buffer, "string2"); 3: strcpy( buffer, "string3"); default: strcpy(buffer, "defaultstring"); } return buffer; } this is c funtion not C++, I think it has to do with type conversion my compiler give warning that declaration of int i shadows a parameter.

    Read the article

  • Binary file reading problem

    - by ScReYm0
    Ok i have problem with my code for reading binary file... First i will show you my writing code: void book_saving(char *file_name, struct BOOK *current) { FILE *out; BOOK buf; out = fopen(file_name, "wb"); if(out != NULL) { printf_s("Writting to file..."); do { if(current != NULL) { strcpy(buf.catalog_number, current->catalog_number); strcpy(buf.author, current->author); buf.price = current->price; strcpy(buf.publisher, current->publisher); strcpy(buf.title, current->title); buf.price = current->year_published; fwrite(&buf, sizeof(BOOK), 1, out); } current = current->next; }while(current != NULL); printf_s("Done!\n"); fclose(out); } } and here is my "version" for reading it back: int book_open(struct BOOK *current, char *file_name) { FILE *in; BOOK buf; BOOK *vnext; int count; int i; in = fopen("west", "rb"); printf_s("Reading database from %s...", file_name); if(!in) { printf_s("\nERROR!"); return 1; } i = fread(&buf,sizeof(BOOK), 1, in); while(!feof(in)) { if(current != NULL) { current = malloc(sizeof(BOOK)); current->next = NULL; } strcpy(current->catalog_number, buf.catalog_number); strcpy(current->title, buf.title); strcpy(current->publisher, buf.publisher); current->price = buf.price; current->year_published = buf.year_published; fread(&buf, 1, sizeof(BOOK), in); while(current->next != NULL) current = current->next; fclose(in); } printf_s("Done!"); return 0; } I just need to save my linked list in binary file and to be able to read it back ... please help me. The program just don't read it or its crash every time different situation ...

    Read the article

  • binary files writing/reading problems...

    - by ScReYm0
    Ok i have problem with my code for reading binary file... First i will show you my writing code: void book_saving(char *file_name, struct BOOK *current) { FILE *out; BOOK buf; out = fopen(file_name, "wb"); if(out != NULL) { printf_s("Writting to file..."); do { if(current != NULL) { strcpy(buf.catalog_number, current-catalog_number); strcpy(buf.author, current-author); buf.price = current-price; strcpy(buf.publisher, current-publisher); strcpy(buf.title, current-title); buf.price = current-year_published; fwrite(&buf, sizeof(BOOK), 1, out); } current = current-next; }while(current != NULL); printf_s("Done!\n"); fclose(out); } } and here is my "version" for reading: int book_open(struct BOOK *current, char *file_name) { FILE *in; BOOK buf; BOOK *vnext; int count; int i; in = fopen("west", "rb"); printf_s("Reading database from %s...", file_name); if(!in) { printf_s("\nERROR!"); return 1; } i = fread(&buf,sizeof(BOOK), 1, in); while(!feof(in)) { if(current != NULL) { current = malloc(sizeof(BOOK)); current-next = NULL; } strcpy(current-catalog_number, buf.catalog_number); strcpy(current-title, buf.title); strcpy(current-publisher, buf.publisher); current-price = buf.price; current-year_published = buf.year_published; fread(&buf, 1, sizeof(BOOK), in); while(current-next != NULL) current = current-next; fclose(in); } printf_s("Done!"); return 0; } I just need to save my linked list in binary file and to be able to read it back ... please help me. The program just don't read it or its crash every time different situation ...

    Read the article

  • C - array count, strtok, etc

    - by Pedro
    Hi... i have a little problem on my code... HI open a txt that have this: LEI;7671;Maria Albertina da silva;[email protected]; 9;8;12;9;12;11;6;15;7;11; LTCGM;6567;Artur Pereira Ribeiro;[email protected]; 6;13;14;12;11;16;14; LEI;7701;Ana Maria Carvalho;[email protected]; 8;13;11;7;14;12;11;16;14; LEI, LTCGM are the college; 7671, 6567, 7701 is student number; Maria, Artur e Ana are the students name; [email protected], ...@gmail are emails from students; the first number of every line is the total of classes that students have; after that is students school notes; example: College: LEI Number: 7671 Name: Maria Albertina da Silva email: [email protected] total of classes: 9 Classe Notes: 8 12 9 12 11 6 15 7 11. My code: typedef struct aluno{ char sigla[5];//college char numero[80];//number char nome[80];//student name char email[20];//email int total_notas;// total of classes char tot_not[40]; // total classes char notas[20];// classe notes int nota; //class notes char situacao[80]; //situation (aproved or disaproved) }ALUNO; void ordena(ALUNO*alunos, int tam)//bubble sort { int i=0; int j=0; char temp[100]; for( i=0;i<tam;i++) for(j=0;j<tam-1;j++) if(strcmp( alunos[i].sigla[j], alunos[i].sigla[j+1])>0){ strcpy(temp, alunos[i].sigla[j]); strcpy(alunos[i].sigla[j],alunos[i].sigla[j+1]); strcpy(alunos[i].sigla[j+1], temp); } } void xml(ALUNO*alunos, int tam){ FILE *fp; char linha[60];//line int soma, max, min, count;//biggest note and lowest note and students per course count float media; //media of notes fp=fopen("example.txt","r"); if(fp==NULL){ exit(1); } else{ while(!(feof(fp))){ soma=0; media=0; max=0; min=0; count=0; fgets(linha,60,fp); if(linha[0]=='L'){ if(ap_dados=strtok(linha,";")){ strcpy(alunos[i].sigla,ap_dados);//copy to struct // i need to call bubble sort here, but i don't know how printf("College: %s\n",alunos[i].sigla); if(ap_dados=strtok(NULL,";")){ strcpy(alunos[i].numero,ap_dados);//copy to struct printf("number: %s\n",alunos[i].numero); if(ap_dados=strtok(NULL,";")){ strcpy(alunos[i].nome, ap_dados);//copy to struct printf("name: %s\n",alunos[i].nome); if(ap_dados=strtok(NULL,";")){ strcpy(alunos[i].email, ap_dados);//copy to struct printf("email: %s\n",alunos[i].email); } } } }i++; } if(isdigit(linha[0])){ if(info_notas=strtok(linha,";")){ strcpy(alunos[i].tot_not,info_notas); alunos[i].total_notas=atoi(alunos[i].tot_not);//total classes for(z=0;z<=alunos[i].total_notas;z++){ if(info_notas=strtok(NULL,";")){ strcpy(alunos[i].notas,info_notas); alunos[i].nota=atoi(alunos[i].notas); // student class notes } soma=soma + alunos[i].nota; media=soma/alunos[i].total_notas;//doesn't work if(alunos[i].nota>max){ max=alunos[i].nota;;//doesn't work } else{ if(min<alunos[i].nota){ min=alunos[i].nota;;//doesn't work } } //now i need to count the numbers of students in the same college, but doesn't work /*If(strcmp(alunos[i].sigla, alunos[i+1].sigla)=0){ count ++; printf("%d\n", count); here for LEI should appear 2 students and for LTCGM appear 1, don't work }*/ //Now i need to see if student is aproved or disaproved // Student is disaproved if he gets 3 notes under 10, how can i do that? } printf("media %d\n",media); //media printf("Nota maxima %d\n",max);// biggest note printf("Nota minima %d\n",min); //lowest note }i++; } } } fclose(fp); } int main(int argc, char *argv[]){ ALUNO alunos; FILE *fp; int tam; fp=fopen(nomeFicheiro,"r"); alunos = (ALUNO*) calloc (tam, sizeof(ALUNO)); xml(alunos,nomeFicheiro, tam); system("PAUSE"); return 0; }

    Read the article

  • how to insert multiple characters into a string in C [closed]

    - by John Li
    I wish to insert some characters into a string in C: Example: char string[20] = "20120910T090000"; I want to make it something like "2012-09-10-T-0900-00" My code so far: void append(char subject[],char insert[], int pos) { char buf[100]; strncpy(buf, subject, pos); int len = strlen(buf); strcpy(buf+len, insert); len += strlen(insert); strcpy(buf+len, subject+pos); strcpy(subject, buf); } When I call this the first time I get: 2012-0910T090000 However when I call it a second time I get: 2012-0910T090000-10T090000 Any help is appreciated

    Read the article

  • C++ cin keeps skipping.....

    - by user69514
    I am having problems with my program. WHen I run it, it asks the user for the album, the title, but then it just exits the loop without asking for the price and the sale tax. Any ideas what's going on? This is a sample run Discounts effective for September 15, 2010 Classical 8% Country 4% International 17% Jazz 0% Rock 16% Show 12% Are there more transactions? Y/N y Enter Artist of CD: Sevendust Enter Title of CD: Self titled Enter Genre of CD: Rock enter price Are there more transactions? Y/N Thank you for shopping with us! Program code: #include <iostream> #include <string> using namespace std; int counter = 0; string discount_tiles[] = {"Classical", "Country", "International", "Jazz", "Rock", "Show"}; int discount_amounts[] = {8, 4, 17, 0, 16, 12, 14}; string date = "September 15, 2010"; // Array Declerations //Artist array char** artist = new char *[100]; //Title array char** title = new char *[100]; //Genres array char** genres = new char *[100]; //Price array double* price[100]; //Discount array double* tax[100]; // sale price array double* sale_price[100]; //sale tax array double* sale_tax[100]; //cash price array double* cash_price[100]; //Begin Prototypes char* getArtist(); char* getTitle(); char* getGenre(); double* getPrice(); double* getTax(); unsigned int* AssignDiscounts(); void ReadTransaction (char ** artist, char ** title, char ** genre, float ** cash, float & taxrate, int albumcount); void computesaleprice(); bool AreThereMore (); //End Prototypes bool areThereMore () { char answer; cout << "Are there more transactions? Y/N" << endl; cin >> answer; if (answer =='y' || answer =='Y') return true; else return false; } char* getArtist() { char * artist= new char [100]; cout << "Enter Artist of CD: " << endl; cin.getline(artist,100); cin.ignore(); return artist; } char* getTitle() { char * title= new char [100]; cout << "Enter Title of CD: " << endl; cin.getline(title,100); cin.ignore(); return title; } char* getGenre() { char * genre= new char [100]; cout << "Enter Genre of CD: " << endl; cin.getline(genre,100); cin.ignore(); return genre; } double* getPrice() { //double* price = new double(); //cout << "Enter Price of CD: " << endl; //cin >> *price; //return price; double p = 0.0; cout<< "enter price" << endl; cin >> p; cin.ignore(); double* pp = &p; return pp; } double* getTax() { double* tax= new double(); cout << "Enter local sales tax: " << endl; cin >> *tax; return tax; } int findDiscount(string str){ if(str.compare(discount_tiles[0]) == 0) return discount_amounts[0]; else if(str.compare(discount_tiles[0]) == 0) return discount_amounts[1]; else if(str.compare(discount_tiles[0]) == 0) return discount_amounts[2]; else if(str.compare(discount_tiles[0]) == 0) return discount_amounts[3]; else if(str.compare(discount_tiles[0]) == 0) return discount_amounts[4]; else if(str.compare(discount_tiles[0]) == 0) return discount_amounts[5]; else{ cout << "Error in findDiscount function" << endl; return 0; } } void computesaleprice() { /** fill in array for all purchases **/ for( int i=0; i<=counter; i++){ double temp = *price[i]; temp -= findDiscount(genres[i]); double* tmpPntr = new double(); tmpPntr = &temp; sale_price[i] = tmpPntr; delete(&temp); delete(tmpPntr); } } void printDailyDiscounts(){ cout << "Discounts effective for " << date << endl; for(int i=0; i < 6; i++){ cout << discount_tiles[i] << "\t" << discount_amounts[i] << "%" << endl; } } //Begin Main int main () { for( int i=0; i<100; i++){ artist[i]=new char [100]; title[i]=new char [100]; genres[i]=new char [100]; price[i] = new double(0.0); tax[i] = new double(0.0); } // End Array Decleration printDailyDiscounts(); bool flag = true; while(flag == true){ if(areThereMore() == true){ artist[counter] = getArtist(); title[counter] = getTitle(); genres[counter] = getGenre(); price[counter] = getPrice(); //tax[counter] = getTax(); //counter++; flag = true; } else { flag = false; } } //compute sale prices //computesaleprice(); cout << "Thank you for shopping with us!" << endl; return 0; } //End Main /** void ReadTransaction (char ** artist, char ** title, char ** genre, float ** cash, float & taxrate, int albumcount) { strcpy(artist[albumcount],getArtist()); strcpy(title[albumcount],getTitle()); strcpy(genre[albumcount],getGenre()); //cash[albumcount][0]=computesaleprice();??????? //taxrate=getTax;?????????????? } * * */ unsigned int * AssignDiscounts() { unsigned int * discount = new unsigned int [7]; cout << "Enter Classical Discount: " << endl; cin >> discount[0]; cout << "Enter Country Discount: " << endl; cin >> discount[1]; cout << "Enter International Discount: " << endl; cin >> discount[2]; cout << "Enter Jazz Discount: " << endl; cin >> discount[3]; cout << "Enter Pop Discount: " << endl; cin >> discount[4]; cout << "Enter Rock Discount: " << endl; cin >> discount[5]; cout << "Enter Show Discount: " << endl; cin >> discount[6]; return discount; } /** char ** AssignGenres () { char ** genres = new char * [7]; for (int x=0;x<7;x++) genres[x] = new char [20]; strcpy(genres [0], "Classical"); strcpy(genres [1], "Country"); strcpy(genres [2], "International"); strcpy(genres [3], "Jazz"); strcpy(genres [4], "Pop"); strcpy(genres [5], "Rock"); strcpy(genres [6], "Show"); return genres; } **/ float getTax(float taxrate) { cout << "Please enter store tax rate: " << endl; cin >> taxrate; return taxrate; }

    Read the article

  • Header Guard Issues - Getting Swallowed Alive

    - by gjnave
    I'm totally at wit's end: I can't figure out how my dependency issues. I've read countless posts and blogs and reworked my code so many times that I can't even remember what almost worked and what didnt. I continually get not only redefinition errors, but class not defined errors. I rework the header guards and remove some errors simply to find others. I somehow got everything down to one error but then even that got broke while trying to fix it. Would you please help me figure out the problem? card.cpp #include <iostream> #include <cctype> #include "card.h" using namespace std; // ====DECL====== Card::Card() { abilities = 0; flavorText = 0; keywords = 0; artifact = 0; classType = new char[strlen("Card") + 1]; classType = "Card"; } Card::~Card (){ delete name; delete abilities; delete flavorText; artifact = NULL; } // ------------ Card::Card(const Card & to_copy) { name = new char[strlen(to_copy.name) +1]; // creating dynamic array strcpy(to_copy.name, name); type = to_copy.type; color = to_copy.color; manaCost = to_copy.manaCost; abilities = new char[strlen(to_copy.abilities) +1]; strcpy(abilities, to_copy.abilities); flavorText = new char[strlen(to_copy.flavorText) +1]; strcpy(flavorText, to_copy.flavorText); keywords = new char[strlen(to_copy.keywords) +1]; strcpy(keywords, to_copy.keywords); inPlay = to_copy.inPlay; tapped = to_copy.tapped; enchanted = to_copy.enchanted; cursed = to_copy.cursed; if (to_copy.type != ARTIFACT) artifact = to_copy.artifact; } // ====DECL===== int Card::equipArtifact(Artifact* to_equip){ artifact = to_equip; } Artifact * Card::unequipArtifact(Card * unequip_from){ Artifact * to_remove = artifact; artifact = NULL; return to_remove; // put card in hand or in graveyard } int Card::enchant( Card * to_enchant){ to_enchant->enchanted = true; cout << "enchanted" << endl; } int Card::disenchant( Card * to_disenchant){ to_disenchant->enchanted = false; cout << "Enchantment Removed" << endl; } // ========DECL===== Spell::Spell() { currPower = basePower; currToughness = baseToughness; classType = new char[strlen("Spell") + 1]; classType = "Spell"; } Spell::~Spell(){} // --------------- Spell::Spell(const Spell & to_copy){ currPower = to_copy.currPower; basePower = to_copy.basePower; currToughness = to_copy.currToughness; baseToughness = to_copy.baseToughness; } // ========= int Spell::attack( Spell *& blocker ){ blocker->currToughness -= currPower; currToughness -= blocker->currToughness; } //========== int Spell::counter (Spell *& to_counter){ cout << to_counter->name << " was countered by " << name << endl; } // ============ int Spell::heal (Spell *& to_heal, int amountOfHealth){ to_heal->currToughness += amountOfHealth; } // ------- Creature::Creature(){ summoningSick = true; } // =====DECL====== Land::Land(){ color = NON; classType = new char[strlen("Land") + 1]; classType = "Land"; } // ------ int Land::generateMana(int mana){ // ... // } card.h #ifndef CARD_H #define CARD_H #include <cctype> #include <iostream> #include "conception.h" class Artifact; class Spell; class Card : public Conception { public: Card(); Card(const Card &); ~Card(); protected: char* name; enum CardType { INSTANT, CREATURE, LAND, ENCHANTMENT, ARTIFACT, PLANESWALKER}; enum CardColor { WHITE, BLUE, BLACK, RED, GREEN, NON }; CardType type; CardColor color; int manaCost; char* abilities; char* flavorText; char* keywords; bool inPlay; bool tapped; bool cursed; bool enchanted; Artifact* artifact; virtual int enchant( Card * ); virtual int disenchant (Card * ); virtual int equipArtifact( Artifact* ); virtual Artifact* unequipArtifact(Card * ); }; // ------------ class Spell: public Card { public: Spell(); ~Spell(); Spell(const Spell &); protected: virtual int heal( Spell *&, int ); virtual int attack( Spell *& ); virtual int counter( Spell*& ); int currToughness; int baseToughness; int currPower; int basePower; }; class Land: public Card { public: Land(); ~Land(); protected: virtual int generateMana(int); }; class Forest: public Land { public: Forest(); ~Forest(); protected: int generateMana(); }; class Creature: public Spell { public: Creature(); ~Creature(); protected: bool summoningSick; }; class Sorcery: public Spell { public: Sorcery(); ~Sorcery(); protected: }; #endif conception.h -- this is an "uber class" from which everything derives class Conception{ public: Conception(); ~Conception(); protected: char* classType; }; conception.cpp Conception::Conception{ Conception(){ classType = new char[11]; char = "Conception"; } game.cpp -- this is an incomplete class as of this code #include <iostream> #include <cctype> #include "game.h" #include "player.h" Battlefield::Battlefield(){ card = 0; } Battlefield::~Battlefield(){ delete card; } Battlefield::Battlefield(const Battlefield & to_copy){ } // =========== /* class Game(){ public: Game(); ~Game(); protected: Player** player; // for multiple players Battlefield* root; // for battlefield getPlayerMove(); // ask player what to do addToBattlefield(); removeFromBattlefield(); sendAttack(); } */ #endif game.h #ifndef GAME_H #define GAME_H #include "list.h" class CardList(); class Battlefield : CardList{ public: Battlefield(); ~Battlefield(); protected: Card* card; // make an array }; class Game : Conception{ public: Game(); ~Game(); protected: Player** player; // for multiple players Battlefield* root; // for battlefield getPlayerMove(); // ask player what to do addToBattlefield(); removeFromBattlefield(); sendAttack(); Battlefield* field; }; list.cpp #include <iostream> #include <cctype> #include "list.h" // ========== LinkedList::LinkedList(){ root = new Node; classType = new char[strlen("LinkedList") + 1]; classType = "LinkedList"; }; LinkedList::~LinkedList(){ delete root; } LinkedList::LinkedList(const LinkedList & obj) { // code to copy } // --------- // ========= int LinkedList::delete_all(Node* root){ if (root = 0) return 0; delete_all(root->next); root = 0; } int LinkedList::add( Conception*& is){ if (root == 0){ root = new Node; root->next = 0; } else { Node * curr = root; root = new Node; root->next=curr; root->it = is; } } int LinkedList::remove(Node * root, Node * prev, Conception* is){ if (root = 0) return -1; if (root->it == is){ root->next = root->next; return 0; } remove(root->next, root, is); return 0; } Conception* LinkedList::find(Node*& root, const Conception* is, Conception* holder = NULL) { if (root==0) return NULL; if (root->it == is){ return root-> it; } holder = find(root->next, is); return holder; } Node* LinkedList::goForward(Node * root){ if (root==0) return root; if (root->next == 0) return root; else return root->next; } // ============ Node* LinkedList::goBackward(Node * root){ root = root->prev; } list.h #ifndef LIST_H #define LIST_H #include <iostream> #include "conception.h" class Node : public Conception { public: Node() : next(0), prev(0), it(0) { it = 0; classType = new char[strlen("Node") + 1]; classType = "Node"; }; ~Node(){ delete it; delete next; delete prev; } Node* next; Node* prev; Conception* it; // generic object }; // ---------------------- class LinkedList : public Conception { public: LinkedList(); ~LinkedList(); LinkedList(const LinkedList&); friend bool operator== (Conception& thing_1, Conception& thing_2 ); protected: virtual int delete_all(Node*); virtual int add( Conception*& ); // virtual Conception* find(Node *&, const Conception*, Conception* ); // virtual int remove( Node *, Node *, Conception* ); // removes question with keyword int display_all(node*& ); virtual Node* goForward(Node *); virtual Node* goBackward(Node *); Node* root; // write copy constrcutor }; // ============= class CircularLinkedList : public LinkedList { public: // CircularLinkedList(); // ~CircularLinkedList(); // CircularLinkedList(const CircularLinkedList &); }; class DoubleLinkedList : public LinkedList { public: // DoubleLinkedList(); // ~DoubleLinkedList(); // DoubleLinkedList(const DoubleLinkedList &); protected: }; // END OF LIST Hierarchy #endif player.cpp #include <iostream> #include "player.h" #include "list.h" using namespace std; Library::Library(){ root = 0; } Library::~Library(){ delete card; } // ====DECL========= Player::~Player(){ delete fname; delete lname; delete deck; } Wizard::~Wizard(){ delete mana; delete rootL; delete rootH; } // =====Player====== void Player::changeName(const char[] first, const char[] last){ char* backup1 = new char[strlen(fname) + 1]; strcpy(backup1, fname); char* backup2 = new char[strlen(lname) + 1]; strcpy(backup1, lname); if (first != NULL){ fname = new char[strlen(first) +1]; strcpy(fname, first); } if (last != NULL){ lname = new char[strlen(last) +1]; strcpy(lname, last); } return 0; } // ========== void Player::seeStats(Stats*& to_put){ to_put->wins = stats->wins; to_put->losses = stats->losses; to_put->winRatio = stats->winRatio; } // ---------- void Player::displayDeck(const LinkedList* deck){ } // ================ void CardList::findCard(Node* root, int id, NodeCard*& is){ if (root == NULL) return; if (root->it.id == id){ copyCard(root->it, is); return; } else findCard(root->next, id, is); } // -------- void CardList::deleteAll(Node* root){ if (root == NULL) return; deleteAll(root->next); root->next = NULL; } // --------- void CardList::removeCard(Node* root, int id){ if (root == NULL) return; if (root->id = id){ root->prev->next = root->next; // the prev link of root, looks back to next of prev node, and sets to where root next is pointing } return; } // --------- void CardList::addCard(Card* to_add){ if (!root){ root = new Node; root->next = NULL; root->prev = NULL; root->it = &to_add; return; } else { Node* original = root; root = new Node; root->next = original; root->prev = NULL; original->prev = root; } } // ----------- void CardList::displayAll(Node*& root){ if (root == NULL) return; cout << "Card Name: " << root->it.cardName; cout << " || Type: " << root->it.type << endl; cout << " --------------- " << endl; if (root->classType == "Spell"){ cout << "Base Power: " << root->it.basePower; cout << " || Current Power: " << root->it.currPower << endl; cout << "Base Toughness: " << root->it.baseToughness; cout << " || Current Toughness: " << root->it.currToughness << endl; } cout << "Card Type: " << root->it.currPower; cout << " || Card Color: " << root->it.color << endl; cout << "Mana Cost" << root->it.manaCost << endl; cout << "Keywords: " << root->it.keywords << endl; cout << "Flavor Text: " << root->it.flavorText << endl; cout << " ----- Class Type: " << root->it.classType << " || ID: " << root->it.id << " ----- " << endl; cout << " ******************************************" << endl; cout << endl; // ------- void CardList::copyCard(const Card& to_get, Card& put_to){ put_to.type = to_get.type; put_to.color = to_get.color; put_to.manaCost = to_get.manaCost; put_to.inPlay = to_get.inPlay; put_to.tapped = to_get.tapped; put_to.class = to_get.class; put_to.id = to_get.id; put_to.enchanted = to_get.enchanted; put_to.artifact = to_get.artifact; put_to.class = to_get.class; put.to.abilities = new char[strlen(to_get.abilities) +1]; strcpy(put_to.abilities, to_get.abilities); put.to.keywords = new char[strlen(to_get.keywords) +1]; strcpy(put_to.keywords, to_get.keywords); put.to.flavorText = new char[strlen(to_get.flavorText) +1]; strcpy(put_to.flavorText, to_get.flavorText); if (to_get.class = "Spell"){ put_to.baseToughness = to_get.baseToughness; put_to.basePower = to_get.basePower; put_to.currToughness = to_get.currToughness; put_to.currPower = to_get.currPower; } } // ---------- player.h #ifndef player.h #define player.h #include "list.h" // ============ class CardList() : public LinkedList(){ public: CardList(); ~CardList(); protected: virtual void findCard(Card&); virtual void addCard(Card* ); virtual void removeCard(Node* root, int id); virtual void deleteAll(); virtual void displayAll(); virtual void copyCard(const Conception*, Node*&); Node* root; } // --------- class Library() : public CardList(){ public: Library(); ~Library(); protected: Card* card; int numCards; findCard(Card&); // get Card and fill empty template } // ----------- class Deck() : public CardList(){ public: Deck(); ~Deck(); protected: enum deckColor { WHITE, BLUE, BLACK, RED, GREEN, MIXED }; char* deckName; } // =============== class Mana(int amount) : public Conception { public: Mana() : displayTotal(0), classType(0) { displayTotal = 0; classType = new char[strlen("Mana") + 1]; classType = "Mana"; }; protected: int accrued; void add(); void remove(); int displayTotal(); } inline Mana::add(){ accrued += 1; } inline Mana::remove(){ accrued -= 1; } inline Mana::displayTotal(){ return accrued; } // ================ class Stats() : public Conception { public: friend class Player; friend class Game; Stats() : wins(0), losses(0), winRatio(0) { wins = 0; losses = 0; if ( (wins + losses != 0) winRatio = wins / (wins + losses); else winRatio = 0; classType = new char[strlen("Stats") + 1]; classType = "Stats"; } protected: int wins; int losses; float winRatio; void int getStats(Stats*& ); } // ================== class Player() : public Conception{ public: Player() : wins(0), losses(0), winRatio(0) { fname = NULL; lname = NULL; stats = NULL; CardList = NULL; classType = new char[strlen("Player") + 1]; classType = "Player"; }; ~Player(); Player(const Player & obj); protected: // member variables char* fname; char* lname; Stats stats; // holds previous game statistics CardList* deck[]; // hold multiple decks that player might use - put ll in this private: // member functions void changeName(const char[], const char[]); void shuffleDeck(int); void seeStats(Stats*& ); void displayDeck(int); chooseDeck(); } // -------------------- class Wizard(Card) : public Player(){ public: Wizard() : { mana = NULL; rootL = NULL; rootH = NULL}; ~Wizard(); protected: playCard(const Card &); removeCard(Card &); attackWithCard(Card &); enchantWithCard(Card &); disenchantWithCard(Card &); healWithCard(Card &); equipWithCard(Card &); Mana* mana[]; Library* rootL; // Library Library* rootH; // Hand } #endif

    Read the article

  • bubble sort on array of c structures not sorting properly

    - by xmpirate
    I have the following program for books record and I want to sort the records on name of book. the code isn't showing any error but it's not sorting all the records. #include "stdio.h" #include "string.h" #define SIZE 5 struct books{ //define struct char name[100],author[100]; int year,copies; }; struct books book1[SIZE],book2[SIZE],*pointer; //define struct vars void sort(struct books *,int); //define sort func main() { int i; char c; for(i=0;i<SIZE;i++) //scanning values { gets(book1[i].name); gets(book1[i].author); scanf("%d%d",&book1[i].year,&book1[i].copies); while((c = getchar()) != '\n' && c != EOF); } pointer=book1; sort(pointer,SIZE); //sort call i=0; //printing values while(i<SIZE) { printf("##########################################################################\n"); printf("Book: %s\nAuthor: %s\nYear of Publication: %d\nNo of Copies: %d\n",book1[i].name,book1[i].author,book1[i].year,book1[i].copies); printf("##########################################################################\n"); i++; } } void sort(struct books *pointer,int n) { int i,j,sorted=0; struct books temp; for(i=0;(i<n-1)&&(sorted==0);i++) //bubble sort on the book name { sorted=1; for(j=0;j<n-i-1;j++) { if(strcmp((*pointer).name,(*(pointer+1)).name)>0) { //copy to temp val strcpy(temp.name,(*pointer).name); strcpy(temp.author,(*pointer).author); temp.year=(*pointer).year; temp.copies=(*pointer).copies; //copy next val strcpy((*pointer).name,(*(pointer+1)).name); strcpy((*pointer).author,(*(pointer+1)).author); (*pointer).year=(*(pointer+1)).year; (*pointer).copies=(*(pointer+1)).copies; //copy back temp val strcpy((*(pointer+1)).name,temp.name); strcpy((*(pointer+1)).author,temp.author); (*(pointer+1)).year=temp.year; (*(pointer+1)).copies=temp.copies; sorted=0; } *pointer++; } } } My Imput The C Programming Language X Y Z 1934 56 Inferno Dan Brown 1993 453 harry Potter and the soccers stone J K Rowling 2012 150 Ruby On Rails jim aurther nil 2004 130 Learn Python Easy Way gmaps4rails 1967 100 And the output ########################################################################## Book: Inferno Author: Dan Brown Year of Publication: 1993 No of Copies: 453 ########################################################################## ########################################################################## Book: The C Programming Language Author: X Y Z Year of Publication: 1934 No of Copies: 56 ########################################################################## ########################################################################## Book: Ruby On Rails Author: jim aurther nil Year of Publication: 2004 No of Copies: 130 ########################################################################## ########################################################################## Book: Learn Python Easy Way Author: gmaps4rails Year of Publication: 1967 No of Copies: 100 ########################################################################## ########################################################################## Book: Author: Year of Publication: 0 No of Copies: 0 ########################################################################## We can see the above sorting is wrong? What I'm I doing wrong?

    Read the article

  • socket operation on nonsocket or bad file descriptor

    - by Magn3s1um
    I'm writing a pthread server which takes requests from clients and sends them back a bunch of .ppm files. Everything seems to go well, but sometimes when I have just 1 client connected, when trying to read from the file descriptor (for the file), it says Bad file Descriptor. This doesn't make sense, since my int fd isn't -1, and the file most certainly exists. Other times, I get this "Socket operation on nonsocket" error. This is weird because other times, it doesn't give me this error and everything works fine. When trying to connect multiple clients, for some reason, it will only send correctly to one, and then the other client gets the bad file descriptor or "nonsocket" error, even though both threads are processing the same messages and do the same routines. Anyone have an idea why? Here's the code that is giving me that error: while(mqueue.head != mqueue.tail && count < dis_m){ printf("Sending to client %s: %s\n", pointer->id, pointer->message); int fd; fd = open(pointer->message, O_RDONLY); char buf[58368]; int bytesRead; printf("This is fd %d\n", fd); bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); fflush(stdout); close(fd); mqueue.mcount--; mqueue.head = mqueue.head->next; free(pointer->message); free(pointer); pointer = mqueue.head; count++; } printf("Sending %s\n", pointer->message); int fd; fd = open(pointer->message, O_RDONLY); printf("This is fd %d\n", fd); printf("I am hhere2\n"); char buf[58368]; int bytesRead; bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); close(fd); mqueue.mcount--; if(mqueue.head != mqueue.tail){ mqueue.head = mqueue.head->next; } else{ mqueue.head->next = malloc(sizeof(struct message)); mqueue.head = mqueue.head->next; mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.head->message = NULL; } free(pointer->message); free(pointer); pthread_mutex_unlock(&numm); pthread_mutex_unlock(&circ); pthread_mutex_unlock(&slots); The messages for both threads are the same, being of the form ./path/imageXX.ppm where XX is the number that should go to the client. The file size of each image is 58368 bytes. Sometimes, this code hangs on the read, and stops execution. I don't know this would be either, because the file descriptor comes back as valid. Thanks in advanced. Edit: Here's some sample output: Sending to client a: ./support/images/sw90.ppm This is fd 4 Error: : Socket operation on non-socket Sending to client a: ./support/images/sw91.ppm This is fd 4 Error: : Socket operation on non-socket Sending ./support/images/sw92.ppm This is fd 4 I am hhere2 Error: : Socket operation on non-socket My dispatcher has defeated evil Sample with 2 clients (client b was serviced first) Sending to client b: ./support/images/sw87.ppm This is fd 6 Error: : Success Sending to client b: ./support/images/sw88.ppm This is fd 6 Error: : Success Sending to client b: ./support/images/sw89.ppm This is fd 6 Error: : Success This is fd 6 Error: : Bad file descriptor Sending to client a: ./support/images/sw85.ppm This is fd 6 Error: As you can see, who ever is serviced first in this instance can open the files, but not the 2nd person. Edit2: Full code. Sorry, its pretty long and terribly formatted. #include <netinet/in.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "ring.h" /* Version 1 Here is what is implemented so far: The threads are created from the arguments specified (number of threads that is) The server will lock and update variables based on how many clients are in the system and such. The socket that is opened when a new client connects, must be passed to the threads. To do this, we need some sort of global array. I did this by specifying an int client and main_pool_busy, and two pointers poolsockets and nonpoolsockets. My thinking on this was that when a new client enters the system, the server thread increments the variable client. When a thread is finished with this client (after it sends it the data), the thread will decrement client and close the socket. HTTP servers act this way sometimes (they terminate the socket as soon as one transmission is sent). *Note down at bottom After the server portion increments the client counter, we must open up a new socket (denoted by new_sd) and get this value to the appropriate thread. To do this, I created global array poolsockets, which will hold all the socket descriptors for our pooled threads. The server portion gets the new socket descriptor, and places the value in the first spot of the array that has a 0. We only place a value in this array IF: 1. The variable main_pool_busy < worknum (If we have more clients in the system than in our pool, it doesn't mean we should always create a new thread. At the end of this, the server signals on the condition variable clientin that a new client has arrived. In our pooled thread, we then must walk this array and check the array until we hit our first non-zero value. This is the socket we will give to that thread. The thread then changes the array to have a zero here. What if our all threads in our pool our busy? If this is the case, then we will know it because our threads in this pool will increment main_pool_busy by one when they are working on a request and decrement it when they are done. If main_pool_busy >= worknum, then we must dynamically create a new thread. Then, we must realloc the size of our nonpoolsockets array by 1 int. We then add the new socket descriptor to our pool. Here's what we need to figure out: NOTE* Each worker should generate 100 messages which specify the worker thread ID, client socket descriptor and a copy of the client message. Additionally, each message should include a message number, starting from 0 and incrementing for each subsequent message sent to the same client. I don't know how to keep track of how many messages were to the same client. Maybe we shouldn't close the socket descriptor, but rather keep an array of structs for each socket that includes how many messages they have been sent. Then, the server adds the struct, the threads remove it, then the threads add it back once they've serviced one request (unless the count is 100). ------------------------------------------------------------- CHANGES Version 1 ---------- NONE: this is the first version. */ #define MAXSLOTS 30 #define dis_m 15 //problems with dis_m ==1 //Function prototypes void inc_clients(); void init_mutex_stuff(pthread_t*, pthread_t*); void *threadpool(void *); void server(int); void add_to_socket_pool(int); void inc_busy(); void dec_busy(); void *dispatcher(); void create_message(long, int, int, char *, char *); void init_ring(); void add_to_ring(char *, char *, int, int, int); int socket_from_string(char *); void add_to_head(char *); void add_to_tail(char *); struct message * reorder(struct message *, struct message *, int); int get_threadid(char *); void delete_socket_messages(int); struct message * merge(struct message *, struct message *, int); int get_request(char *, char *, char*); ///////////////////// //Global mutexes and condition variables pthread_mutex_t startservice; pthread_mutex_t numclients; pthread_mutex_t pool_sockets; pthread_mutex_t nonpool_sockets; pthread_mutex_t m_pool_busy; pthread_mutex_t slots; pthread_mutex_t numm; pthread_mutex_t circ; pthread_cond_t clientin; pthread_cond_t m; /////////////////////////////////////// //Global variables int clients; int main_pool_busy; int * poolsockets, nonpoolsockets; int worknum; struct ring mqueue; /////////////////////////////////////// int main(int argc, char ** argv){ //error handling if not enough arguments to program if(argc != 3){ printf("Not enough arguments to server: ./server portnum NumThreadsinPool\n"); _exit(-1); } //Convert arguments from strings to integer values int port = atoi(argv[1]); worknum = atoi(argv[2]); //Start server portion server(port); } /////////////////////////////////////////////////////////////////////////////////////////////// //The listen server thread///////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////// void server(int port){ int sd, new_sd; struct sockaddr_in name, cli_name; int sock_opt_val = 1; int cli_len; pthread_t threads[worknum]; //create our pthread id array pthread_t dis[1]; //create our dispatcher array (necessary to create thread) init_mutex_stuff(threads, dis); //initialize mutexes and stuff //Server setup /////////////////////////////////////////////////////// if ((sd = socket (AF_INET, SOCK_STREAM, 0)) < 0) { perror("(servConn): socket() error"); _exit (-1); } if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR, (char *) &sock_opt_val, sizeof(sock_opt_val)) < 0) { perror ("(servConn): Failed to set SO_REUSEADDR on INET socket"); _exit (-1); } name.sin_family = AF_INET; name.sin_port = htons (port); name.sin_addr.s_addr = htonl(INADDR_ANY); if (bind (sd, (struct sockaddr *)&name, sizeof(name)) < 0) { perror ("(servConn): bind() error"); _exit (-1); } listen (sd, 5); //End of server Setup ////////////////////////////////////////////////// for (;;) { cli_len = sizeof (cli_name); new_sd = accept (sd, (struct sockaddr *) &cli_name, &cli_len); printf ("Assigning new socket descriptor: %d\n", new_sd); inc_clients(); //New client has come in, increment clients add_to_socket_pool(new_sd); //Add client to the pool of sockets if (new_sd < 0) { perror ("(servConn): accept() error"); _exit (-1); } } pthread_exit(NULL); //Quit } //Adds the new socket to the array designated for pthreads in the pool void add_to_socket_pool(int socket){ pthread_mutex_lock(&m_pool_busy); //Lock so that we can check main_pool_busy int i; //If not all our main pool is busy, then allocate to one of them if(main_pool_busy < worknum){ pthread_mutex_unlock(&m_pool_busy); //unlock busy, we no longer need to hold it pthread_mutex_lock(&pool_sockets); //Lock the socket pool array so that we can edit it without worry for(i = 0; i < worknum; i++){ //Find a poolsocket that is -1; then we should put the real socket there. This value will be changed back to -1 when the thread grabs the sockfd if(poolsockets[i] == -1){ poolsockets[i] = socket; pthread_mutex_unlock(&pool_sockets); //unlock our pool array, we don't need it anymore inc_busy(); //Incrememnt busy (locks the mutex itself) pthread_cond_signal(&clientin); //Signal first thread waiting on a client that a client needs to be serviced break; } } } else{ //Dynamic thread creation goes here pthread_mutex_unlock(&m_pool_busy); } } //Increments the client number. If client number goes over worknum, we must dynamically create new pthreads void inc_clients(){ pthread_mutex_lock(&numclients); clients++; pthread_mutex_unlock(&numclients); } //Increments busy void inc_busy(){ pthread_mutex_lock(&m_pool_busy); main_pool_busy++; pthread_mutex_unlock(&m_pool_busy); } //Initialize all of our mutexes at the beginning and create our pthreads void init_mutex_stuff(pthread_t * threads, pthread_t * dis){ pthread_mutex_init(&startservice, NULL); pthread_mutex_init(&numclients, NULL); pthread_mutex_init(&pool_sockets, NULL); pthread_mutex_init(&nonpool_sockets, NULL); pthread_mutex_init(&m_pool_busy, NULL); pthread_mutex_init(&circ, NULL); pthread_cond_init (&clientin, NULL); main_pool_busy = 0; poolsockets = malloc(sizeof(int)*worknum); int threadreturn; //error checking variables long i = 0; //Loop and create pthreads for(i; i < worknum; i++){ threadreturn = pthread_create(&threads[i], NULL, threadpool, (void *) i); poolsockets[i] = -1; if(threadreturn){ perror("Thread pool created unsuccessfully"); _exit(-1); } } pthread_create(&dis[0], NULL, dispatcher, NULL); } ////////////////////////////////////////////////////////////////////////////////////////// /////////Main pool routines ///////////////////////////////////////////////////////////////////////////////////////// void dec_busy(){ pthread_mutex_lock(&m_pool_busy); main_pool_busy--; pthread_mutex_unlock(&m_pool_busy); } void dec_clients(){ pthread_mutex_lock(&numclients); clients--; pthread_mutex_unlock(&numclients); } //This is what our threadpool pthreads will be running. void *threadpool(void * threadid){ long id = (long) threadid; //Id of this thread int i; int socket; int counter = 0; //Try and gain access to the next client that comes in and wait until server signals that a client as arrived while(1){ pthread_mutex_lock(&startservice); //lock start service (required for cond wait) pthread_cond_wait(&clientin, &startservice); //wait for signal from server that client exists pthread_mutex_unlock(&startservice); //unlock mutex. pthread_mutex_lock(&pool_sockets); //Lock the pool socket so we can get the socket fd unhindered/interrupted for(i = 0; i < worknum; i++){ if(poolsockets[i] != -1){ socket = poolsockets[i]; poolsockets[i] = -1; pthread_mutex_unlock(&pool_sockets); } } printf("Thread #%d is past getting the socket\n", id); int incoming = 1; while(counter < 100 && incoming != 0){ char buffer[512]; bzero(buffer,512); int startcounter = 0; incoming = read(socket, buffer, 512); if(buffer[0] != 0){ //client ID:priority:request:arguments char id[100]; long prior; char request[100]; char arg1[100]; char message[100]; char arg2[100]; char * point; point = strtok(buffer, ":"); strcpy(id, point); point = strtok(NULL, ":"); prior = atoi(point); point = strtok(NULL, ":"); strcpy(request, point); point = strtok(NULL, ":"); strcpy(arg1, point); point = strtok(NULL, ":"); if(point != NULL){ strcpy(arg2, point); } int fd; if(strcmp(request, "start_movie") == 0){ int count = 1; while(count <= 100){ char temp[10]; snprintf(temp, 50, "%d\0", count); strcpy(message, "./support/images/"); strcat(message, arg1); strcat(message, temp); strcat(message, ".ppm"); printf("This is message %s to %s\n", message, id); count++; add_to_ring(message, id, prior, counter, socket); //Adds our created message to the ring counter++; } printf("I'm out of the loop\n"); } else if(strcmp(request, "seek_movie") == 0){ int count = atoi(arg2); while(count <= 100){ char temp[10]; snprintf(temp, 10, "%d\0", count); strcpy(message, "./support/images/"); strcat(message, arg1); strcat(message, temp); strcat(message, ".ppm"); printf("This is message %s\n", message); count++; } } //create_message(id, socket, counter, buffer, message); //Creates our message from the input from the client. Stores it in buffer } else{ delete_socket_messages(socket); break; } } counter = 0; close(socket);//Zero out counter again } dec_clients(); //client serviced, decrement clients dec_busy(); //thread finished, decrement busy } //Creates a message void create_message(long threadid, int socket, int counter, char * buffer, char * message){ snprintf(message, strlen(buffer)+15, "%d:%d:%d:%s", threadid, socket, counter, buffer); } //Gets the socket from the message string (maybe I should just pass in the socket to another method) int socket_from_string(char * message){ char * substr1 = strstr(message, ":"); char * substr2 = substr1; substr2++; int occurance = strcspn(substr2, ":"); char sock[10]; strncpy(sock, substr2, occurance); return atoi(sock); } //Adds message to our ring buffer's head void add_to_head(char * message){ printf("Adding to head of ring\n"); mqueue.head->message = malloc(strlen(message)+1); //Allocate space for message strcpy(mqueue.head->message, message); //copy bytes into allocated space } //Adds our message to our ring buffer's tail void add_to_tail(char * message){ printf("Adding to tail of ring\n"); mqueue.tail->message = malloc(strlen(message)+1); //allocate space for message strcpy(mqueue.tail->message, message); //copy bytes into allocated space mqueue.tail->next = malloc(sizeof(struct message)); //allocate space for the next message struct } //Adds a message to our ring void add_to_ring(char * message, char * id, int prior, int mnum, int socket){ //printf("This is message %s:" , message); pthread_mutex_lock(&circ); //Lock the ring buffer pthread_mutex_lock(&numm); //Lock the message count (will need this to make sure we can't fill the buffer over the max slots) if(mqueue.head->message == NULL){ add_to_head(message); //Adds it to head mqueue.head->socket = socket; //Set message socket mqueue.head->priority = prior; //Set its priority (thread id) mqueue.head->mnum = mnum; //Set its message number (used for sorting) mqueue.head->id = malloc(sizeof(id)); strcpy(mqueue.head->id, id); } else if(mqueue.tail->message == NULL){ //This is the problem for dis_m 1 I'm pretty sure add_to_tail(message); mqueue.tail->socket = socket; mqueue.tail->priority = prior; mqueue.tail->mnum = mnum; mqueue.tail->id = malloc(sizeof(id)); strcpy(mqueue.tail->id, id); } else{ mqueue.tail->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.tail->next; add_to_tail(message); mqueue.tail->socket = socket; mqueue.tail->priority = prior; mqueue.tail->mnum = mnum; mqueue.tail->id = malloc(sizeof(id)); strcpy(mqueue.tail->id, id); } mqueue.mcount++; pthread_mutex_unlock(&circ); if(mqueue.mcount >= dis_m){ pthread_mutex_unlock(&numm); pthread_cond_signal(&m); } else{ pthread_mutex_unlock(&numm); } printf("out of add to ring\n"); fflush(stdout); } ////////////////////////////////// //Dispatcher routines ///////////////////////////////// void *dispatcher(){ init_ring(); while(1){ pthread_mutex_lock(&slots); pthread_cond_wait(&m, &slots); pthread_mutex_lock(&numm); pthread_mutex_lock(&circ); printf("Dispatcher to the rescue!\n"); mqueue.head = reorder(mqueue.head, mqueue.tail, mqueue.mcount); //printf("This is the head %s\n", mqueue.head->message); //printf("This is the tail %s\n", mqueue.head->message); fflush(stdout); struct message * pointer = mqueue.head; int count = 0; while(mqueue.head != mqueue.tail && count < dis_m){ printf("Sending to client %s: %s\n", pointer->id, pointer->message); int fd; fd = open(pointer->message, O_RDONLY); char buf[58368]; int bytesRead; printf("This is fd %d\n", fd); bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); fflush(stdout); close(fd); mqueue.mcount--; mqueue.head = mqueue.head->next; free(pointer->message); free(pointer); pointer = mqueue.head; count++; } printf("Sending %s\n", pointer->message); int fd; fd = open(pointer->message, O_RDONLY); printf("This is fd %d\n", fd); printf("I am hhere2\n"); char buf[58368]; int bytesRead; bytesRead=read(fd,buf,58368); send(pointer->socket,buf,bytesRead,0); perror("Error:\n"); close(fd); mqueue.mcount--; if(mqueue.head != mqueue.tail){ mqueue.head = mqueue.head->next; } else{ mqueue.head->next = malloc(sizeof(struct message)); mqueue.head = mqueue.head->next; mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.head->message = NULL; } free(pointer->message); free(pointer); pthread_mutex_unlock(&numm); pthread_mutex_unlock(&circ); pthread_mutex_unlock(&slots); printf("My dispatcher has defeated evil\n"); } } void init_ring(){ mqueue.head = malloc(sizeof(struct message)); mqueue.head->next = malloc(sizeof(struct message)); mqueue.tail = mqueue.head->next; mqueue.mcount = 0; } struct message * reorder(struct message * begin, struct message * end, int num){ //printf("I am reordering for size %d\n", num); fflush(stdout); int i; if(num == 1){ //printf("Begin: %s\n", begin->message); begin->next = NULL; return begin; } else{ struct message * left = begin; struct message * right; int middle = num/2; for(i = 1; i < middle; i++){ left = left->next; } right = left -> next; left -> next = NULL; //printf("Begin: %s\nLeft: %s\nright: %s\nend:%s\n", begin->message, left->message, right->message, end->message); left = reorder(begin, left, middle); if(num%2 != 0){ right = reorder(right, end, middle+1); } else{ right = reorder(right, end, middle); } return merge(left, right, num); } } struct message * merge(struct message * left, struct message * right, int num){ //printf("I am merginging! left: %s %d, right: %s %dnum: %d\n", left->message,left->priority, right->message, right->priority, num); struct message * start, * point; int lenL= 0; int lenR = 0; int flagL = 0; int flagR = 0; int count = 0; int middle1 = num/2; int middle2; if(num%2 != 0){ middle2 = middle1+1; } else{ middle2 = middle1; } while(lenL < middle1 && lenR < middle2){ count++; //printf("In here for count %d\n", count); if(lenL == 0 && lenR == 0){ if(left->priority < right->priority){ start = left; //Set the start point point = left; //set our enum; left = left->next; //move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else if(left->priority > right->priority){ start = right; point = right; right = right->next; point->next = NULL; lenR++; } else{ if(left->mnum < right->mnum){ ////printf("This is where we are\n"); start = left; //Set the start point point = left; //set our enum; left = left->next; //move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else{ start = right; point = right; right = right->next; point->next = NULL; lenR++; } } } else{ if(left->priority < right->priority){ point->next = left; left = left->next; //move the left pointer point = point->next; point->next = NULL; //Set the next node to NULL lenL++; } else if(left->priority > right->priority){ point->next = right; right = right->next; point = point->next; point->next = NULL; lenR++; } else{ if(left->mnum < right->mnum){ point->next = left; //set our enum; left = left->next; point = point->next;//move the left pointer point->next = NULL; //Set the next node to NULL lenL++; } else{ point->next = right; right = right->next; point = point->next; point->next = NULL; lenR++; } } } if(lenL == middle1){ flagL = 1; break; } if(lenR == middle2){ flagR = 1; break; } } if(flagL == 1){ point->next = right; point = point->next; for(lenR; lenR< middle2-1; lenR++){ point = point->next; } point->next = NULL; mqueue.tail = point; } else{ point->next = left; point = point->next; for(lenL; lenL< middle1-1; lenL++){ point = point->next; } point->next = NULL; mqueue.tail = point; } //printf("This is the start %s\n", start->message); //printf("This is mqueue.tail %s\n", mqueue.tail->message); return start; } void delete_socket_messages(int a){ }

    Read the article

  • Why am I getting 'Heap Corruption'?

    - by fneep
    Please don't crucify me for this one. I decided it might be good to use a char* because the string I intended to build was of a known size. I am also aware that if timeinfo-tm_hour returns something other than 2 digits, things are going to go badly wrong. That said, when this function returns VIsual Studio goes ape at me about HEAP CORRUPTION. What's going wrong? (Also, should I just use a stringbuilder?) void cLogger::_writelogmessage(std::string Message) { time_t rawtime; struct tm* timeinfo = 0; time(&rawtime); timeinfo = localtime(&rawtime); char* MessageBuffer = new char[Message.length()+11]; char* msgptr = MessageBuffer; _itoa(timeinfo->tm_hour, msgptr, 10); msgptr+=2; strcpy(msgptr, "::"); msgptr+=2; _itoa(timeinfo->tm_min, msgptr, 10); msgptr+=2; strcpy(msgptr, "::"); msgptr+=2; _itoa(timeinfo->tm_sec, msgptr, 10); msgptr+=2; strcpy(msgptr, " "); msgptr+=1; strcpy(msgptr, Message.c_str()); _file << MessageBuffer; delete[] MessageBuffer; }

    Read the article

1 2 3 4 5 6 7 8  | Next Page >