question
stringlengths
25
894
answer
stringlengths
4
863
I am doing a ctf problem and there is a line i can't understand. ``` int (*fp)(char *)=(int(*)(char *))&puts, i; ``` Can anyone explain me what does this mean?
fpis a pointer ``` (*fp) ``` to a function ``` (*fp)( ``` that accepts 1 argument of typechar ``` (*fp)(char) ``` and returns a value of typeint ``` int (*fp)(char) ``` The pointer is initialized with the address ofputsafter a mostly redundant conversion. ``` int (*fp)(char *)=(int(*)(char *))&puts int (*fp)(char *)=(int(*)(char *))puts // & redundant int (*fp)(const char *)=puts ``` The objectiis not initialized. It has typeint ``` int (*fp)(char *)=(int(*)(char *))&puts, i; ```
Is there any way to store mobile numbers with starting '0' and having 8 or 9 in c without getting the error invalid 8 or 9 in octal constant?
If you're not planning on doing math on a "number", then use a char array, not an int. Just because something looks like an integer doesn't mean your program should treat it as one.
Thepause()function blocks until a signal arrives. Assuming the process got a signal and pause() returned, does the signal handler will be executedbeforethe code that follows thepause()call, or the result is unexpected? Example: ``` void sigusr1_handler() { // .. handler code } void main() { // .. bind handler to SIGUSR1 pause(); // wait for SIGUSR1 // some more code } ``` Does "some more code" will always be executedaftersigusr1_handler()has finished, or there is a race condition? If so, what is the solution?I cannot think of anything besides busy-waiting, but then the pause won't be needed at all..
Citing fromthe man page for pause(2): pause()returns only when a signal was caught and the signal-catching function returned. In this case,pause()returns -1, anderrnois set toEINTR. You can be sure that your signal handler runs beforesome more code.
I've got this code to populate matrix with 0/1 values and RHO density. I need the same for values from 0 to 2. I mean, the percentage of zeros should be the same, but other values in range 1-2. ``` for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { grid[cur][i][j] = (((float)rand())/RAND_MAX) < rho; } } ``` The only thing I've been able to do is something inelegant like this. This leaves zero/non zero percentage inalterate and random modifies the 1 cells: ``` ... if(grid[cur][i][j] > 0) { grid[cur][i][j] += rand()%2; } ```
I think this code will create 0 with RHO density and other values in range 1-2. ``` for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { grid[cur][i][j] = (((float)rand())/RAND_MAX) < rho ? 0 : rand() % 2 + 1; } } ```
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed6 years ago.Improve this question ``` #include <stdio.h> void swap(int* a, int* b); int main(int argc, const char * argv[]) { int x = 197; int y = 208; printf("x = %d, y = %d\n", x, y); swap(&x, &y); printf("x = %d, y = %d\n", x, y); return 0; } void swap(int* a, int* b) { int temp; temp = *a; *a = *b *b = temp; //invalid operands to binary expression ('int' and 'int *') } ``` Why does the last line give that error?
``` *a = *b *b = temp; ``` Is the same as ``` *a = *b * b = temp; // ^^^^^^ ``` you cannot multiply a int with a pointer
I searched for a long time and couldn't find any websites that describe how to do this. Is eglGetProcAddress the only function needed to do this? I tried the following, but it didn't even compile: ``` GLuint GL_APICALL GL_APIENTRY(*glCreateShader)(GLenum) = (GLuint GL_APICALL GL_APIENTRY(*)(GLenum))eglGetProcAddress("glCreateShader"); ``` I also tried this, but the same error occured: ``` PFNGLCREATESHADERPROC glCreateShader = (PFNGLCREATESHADERPROC)eglGetProcAddress("glCreateShader"); ```
The code I posted above is correct, but the GLES/gl2.h file's function prototypes should be deleted, and the functions should be declared the second way I described above.
``` int main() { char letra = 'B'; int numero = 10; float virgulas = 10.5; char casa = 'Esquina'; printf("%c \n",letra); printf("%d \n",numero); printf("%f \n",virgulas); printf("Letra %c, numero %d, em uma %c\n", letra, numero, casa); return 0; } ``` When I run my code, "Esquina" appears as a random number every time.
"Esquina"is a string. You need to store it in achar*(not achar- most modern compilers should issue an error on this mistake): ``` char* casa = "Esquina"; ``` You can then print it out with the%sformatter (not%c): ``` printf("Letra %c, numero %d, em uma %s\n", letra, numero, casa); /* Here -----------------------------^ */ ```
The following code compiles and runs as I expected. ``` #include <stdio.h> int main(void) { const char C1 = '1'; char const C2 = '3'; printf("%c %c", C1, C2); char *pC1 = &C1; *pC1 = 'H'; char *pC2 = &C2; *pC2 = 'o'; printf("%c %c", C1, C2); return 0; } ``` This code invokes undefined behaviour?
Yes, this code invokes undefined behavior. According to C standard, If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.
I've been looking online for a few hours to find this, but haven't found anything yet that's exactly what I need. I have multiple integers that I need to put into achar*(separated by a space) to be later written to a .txt file. My best attempt until now has been this: ``` char* temp = (char)input.Z_pos_Camera_Temperature; ``` Where input.Z_pos_Camera_Temperature is a member of a struct. I tried ``` char* temp = (char)input.Z_pos_Camera_Temperature + ' ' + input.Z_neg_Camera_Temperature; ``` but that only added the values of the three chars individually. Can someone help me figure this out?
You may want to use snprintf. char buf[32]; snprintf(buf, 32, "%d %d", input.Z_pos_Camera_Temperature, input.Z_neg_Camera_Temperature);
I have come across an array with only one element. This array is defined inside a structure. Which goes like this: ``` typedef struct abc { int variable1; char variable2; float array[1]; }; ``` I don't understand why this array is required, why can't we define just a variable or define a pointer(considering array property). I want to use it. How do i use this variable?abc.array[0]seems correct. Isn't it. AdditionI am not using any dynamic memory allocation then what is its significance ?
It's probably what is called the "struct hack". By allocating a large block of memory, the array becomes dynamic. The one element is just a placeholder to make it compile, in fact there will be many floats. The dynamic array has to be the last element. Use like this: ``` struct abc *ptr = malloc(sizeof(struct abc) + (N-1) * sizeof(float)); ptr->variable1 = N; /* usually store length somewhere in struct*/ ```
The following code compiles and runs as I expected. ``` #include <stdio.h> int main(void) { const char C1 = '1'; char const C2 = '3'; printf("%c %c", C1, C2); char *pC1 = &C1; *pC1 = 'H'; char *pC2 = &C2; *pC2 = 'o'; printf("%c %c", C1, C2); return 0; } ``` This code invokes undefined behaviour?
Yes, this code invokes undefined behavior. According to C standard, If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.
I've been looking online for a few hours to find this, but haven't found anything yet that's exactly what I need. I have multiple integers that I need to put into achar*(separated by a space) to be later written to a .txt file. My best attempt until now has been this: ``` char* temp = (char)input.Z_pos_Camera_Temperature; ``` Where input.Z_pos_Camera_Temperature is a member of a struct. I tried ``` char* temp = (char)input.Z_pos_Camera_Temperature + ' ' + input.Z_neg_Camera_Temperature; ``` but that only added the values of the three chars individually. Can someone help me figure this out?
You may want to use snprintf. char buf[32]; snprintf(buf, 32, "%d %d", input.Z_pos_Camera_Temperature, input.Z_neg_Camera_Temperature);
I have come across an array with only one element. This array is defined inside a structure. Which goes like this: ``` typedef struct abc { int variable1; char variable2; float array[1]; }; ``` I don't understand why this array is required, why can't we define just a variable or define a pointer(considering array property). I want to use it. How do i use this variable?abc.array[0]seems correct. Isn't it. AdditionI am not using any dynamic memory allocation then what is its significance ?
It's probably what is called the "struct hack". By allocating a large block of memory, the array becomes dynamic. The one element is just a placeholder to make it compile, in fact there will be many floats. The dynamic array has to be the last element. Use like this: ``` struct abc *ptr = malloc(sizeof(struct abc) + (N-1) * sizeof(float)); ptr->variable1 = N; /* usually store length somewhere in struct*/ ```
Say that you pass anenvironmentR object to an internal C routine through the.Callinterface. Saidenviromnenthas (by design) asomeObjectobject which I want to extract and manipulate from the C side. How to do it? To simplify my question, I just want to write a C function that returnssomeObject. Like this: ``` en <- new.env() en$someObject <- someValue .Call("extractObject",en) #the above should return en$someObject ``` Guess the C code should then look something like ``` SEXP extractObject(SEXP env) { return SOMEMACROORFUNCTION(env, "someObject"); } ``` Unfortunately, I was not able to find the realSOMEMACROORFUNCTION.
After a little bit of googling and searching, I've found the solution: ``` findVar(install("someObject"),env) ``` in the C code is basically the equivalent ofget("someObject",env)in R.
This question already has answers here:Why can't I increment an array?(5 answers)Closed6 years ago. This code works fine when b is incremented and a is printed upon increment ``` #include<stdio.h> int main() { int a[] = {10,20,30,40,50}, *p, j; int *b = a; for(j=0;j<5;j++) { printf("%d\n",*b); b++; } return 0; } ``` What happens here? What effect does a++ have here to suggestlvalueis required. Does a++ move to a point after all the elements of the array a? ``` #include<stdio.h> int main() { int a[] = {10,20,30,40,50}, *p, j; for(j=0;j<5;j++) { printf("%d\n",*a); a++; } return 0; } ```
ais an array which decays into a (unmodifiable) pointer to the array (and only and always to the array) when used in pointer context. So it cannot be modified, soa++doesn't work. bis a pointer which can point everywhere and thus as well can be modified, sob++works.
I'm using System V to manage a message queue. I successfully made a working prototype, everything works as expected, however I would like to have a LIFO queue instead of FIFO (expected lastmsgsndmessage sent is first readmsgget). Is this possible ?
Yes if you manage correctly message types.msgrcvmanual specifies: The argument msgtyp specifies the type of message requested as follows:If msgtyp is 0, the first message on the queue is received.If msgtyp is greater than 0, the first message of type msgtyp is received.If msgtyp is less than 0, the first message of the lowest type that is less than or equal to the absolute value of msgtyp is received. Then if you send messages with strictly decreasingmsgtyp, an extraction withmsgtypequals toLONG_MINwill always give you the last sent message.msgtypplays the role of a priority in this case, 1 being the greatest.
The below code prints characters till 20th, I want the code to print an error if the string size is more than 20. ``` #include<stdio.h> #include<string.h> int main() { int i = 0, l = 0; char s[20]; fgets(s, 30, stdin); l = strlen(s); if (l < 20) { for (i = 0; i < l; i++) { printf("%c\n", s[i]); } } else printf("Length of the String exceeds the limit."); } ```
Your code contains undefined behaviour if someone enters more that 19 characters. This is becausechar s[20]reserves 20 characters (including string termination character'\0'). So reading in more than 20 characters usingfgets(s,30,stdin)may lead to almost anything, including entering the "wrong" path in the remainder of the program. Trychar s[30]and test your code again.
What isSuper Loopin Embedded C programming language?
This refers to the eternal loop usually located inmain()of a "bare metal" system (no OS), since such systems can never return from main. A typical bare metal embedded system looks like this: ``` void main (void) { // various initializations for(;;) // "super loop" or "main loop" { // do stuff } } ```
I am using struct module for serializing the data to send the data over socket. I observed thatstruct.pack(frmt, value1, ...)returns a string of the value 1 intwo byteshexadecimal format. Why does it returnonly in two bytes format? There should be some reason. Maybe I am missing something while understanding struct class. Thanks in advance.
Read the documentation of thepython struct module If you concern about the size of the packed result readthis
This question already has answers here:Printing out characters in an X pattern using for loops(4 answers)Closed6 years ago. I want to know how to create the following pattern using*and_using nested loops. ``` *_______* __*___* ____* __*___* *_______* ``` I am currently trying to do this in Java, but an answer in C will do as well, I can extrapolate the answer. Here is a pic to better understand the pattern required. I understand that I need to have some code to start with , but I cant manage to work out the logic. Is there any algo/technique that anyone can guide me towards in order to be able to attempt this, some Karnaugh map like technique.
``` for(int i =0; i < 5; i++){ for(int j = 0; j < 9; j++){ if(j==2*i || 8-2*i == j) System.out.print("*"); else if(8-2*i < j && j > 2*i) break; else System.out.print("_"); } System.out.println(); } ```
all I have a few problems with using structures.The source is shown below. main.c ``` #include <stdio.h> #include "info.h" _Rbuffer Rb; void write(_Rbuffer Rb *rb) { printf("write function\n"); } void main(void) { printf("Hello World\n"); } ``` info.h ``` #include <stdint.h> typedef struct { uint8_t Button1; } _Rbuffer; extern _Rbuffer Rb; ``` When compiling, the following error occurs. ``` root@test-VirtualBox:~/sample# gcc main.c main.c:6:24: error: expected ‘;’, ‘,’ or ‘)’ before ‘*’ token void write(_Rbuffer Rb *rb) ^ root@test-VirtualBox:~/sample# ``` I am currently unable to change info.h. I declare a structure and I do not know why an error occurs. How do I fix this?
1 You should useint maininstead ofvoid main. 2 You should usevoid write(_Rbuffer *rb)instead ofvoid write(_Rbuffer Rb *rb).
can someone explain me this code? I cant understand why printed value is 8 in this code can someone explain it to me ``` #include <stdio.h> int f(int i){ switch (i){ case 0 : return 0; case 1: case 2: return 1; default: return f(i-2)+f(i-1); } } void main(void) { printf("%d", f(6)); } ```
Maybe you just need to step through the code in a debug run, but this is why you havef(6)=8 ``` step1: f(6) step2: f(6-2) +f(6-1) step3: f(4-2)+f(4-1) +f(5-2) +f(5-1) step4: f(2) +f(3-2)+f(3-1)+f(3-2)+f(3-1)+f(4-2)+f(4-1) step5: 1 +1 +1 +1 +1 +1 +f(3-2)+f(3-1) step6: 1 +1 +1 +1 +1 +1 +1 +1 final: 8 ```
I've come across some assertions that the behaviour on setting a pointer to something that isn't the address of a scalar or one past the address of a scalar is undefined (with similar restrictions for arrays). So consider this: ``` int main() { int* bar; { int foo = 1; int* b = &foo; bar = b; } int* copy = bar; } ``` Is the behaviour ofint* copy = bar;defined?barno longer points to a scalar as it's out of scope.
The value ofbaris indeterminate after the close bracket. Quoting ISO/IEC 9899:2011, section 6.2.4 §2: […] The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime. The exact behavior ofint* copy = bar;is ambiguous — seeN1793 — Stability of indeterminate values in C11provided byeugene-sh.
I am trying to understand following C program. ``` #include <stdio.h> int main() { int k = m(); printf("%d", k); } void m() { printf("hello"); } ``` Above code produces output ofhello5. I understand why it is printinghello, but I do not understand why there is5behind it. How the5is getting returned and stored into variablek? How does the flow of this program work?
You are assigning return value ofm()tok. Sincem()has no return value undefined behaviour will be visible, so there will be "garbage" ink(in this case: 5).
Say I have a struct with 2 fields and the implementation of C that I have also has some padding between these fields. If I create two variables of the struct and assign one to another, will the padding be guaranteed to be equal? I know that for most compilers it would be so (because they just call memcpy), but I want to know what is specified about the padding in the standard? Intention for this question is, can I usememcmpto check equality of structs. Say I have a compiler which emits code that just assigns all the members of the struct instead of doingmemcpy, will it be a valid implementation of the assignment of struct operation?
The standard says in anote 51 of6.2.6.1 General: Thus, for example, structure assignment need not copy any padding bits.
I want to initialize an array of variable length with random zeros and ones. My problem is that the array I created seems to only have a length of 4 elements. Why is that? ``` int main() { int i, j; int length = 20; int *array = (int *) calloc(length, sizeof(int)); for (i = 1; i < length; i++) { array[i] = 1; printf("%d", array[i]); } printf("\n"); for (j = 0; j < sizeof(array); j++) { printf("%d", array[j]); } getchar(); } ```
The type ofarrayisint *, so the size ofarrayin the sense ofsizeof(array)is the size of a pointer value (i.e. 4 on 32 bit systems and 8 on 64 bit systems). You should simply writefor (j = 0; j < length; j++)instead offor (j = 0; j < sizeof(array); j++).
Say I have a struct with 2 fields and the implementation of C that I have also has some padding between these fields. If I create two variables of the struct and assign one to another, will the padding be guaranteed to be equal? I know that for most compilers it would be so (because they just call memcpy), but I want to know what is specified about the padding in the standard? Intention for this question is, can I usememcmpto check equality of structs. Say I have a compiler which emits code that just assigns all the members of the struct instead of doingmemcpy, will it be a valid implementation of the assignment of struct operation?
The standard says in anote 51 of6.2.6.1 General: Thus, for example, structure assignment need not copy any padding bits.
I want to initialize an array of variable length with random zeros and ones. My problem is that the array I created seems to only have a length of 4 elements. Why is that? ``` int main() { int i, j; int length = 20; int *array = (int *) calloc(length, sizeof(int)); for (i = 1; i < length; i++) { array[i] = 1; printf("%d", array[i]); } printf("\n"); for (j = 0; j < sizeof(array); j++) { printf("%d", array[j]); } getchar(); } ```
The type ofarrayisint *, so the size ofarrayin the sense ofsizeof(array)is the size of a pointer value (i.e. 4 on 32 bit systems and 8 on 64 bit systems). You should simply writefor (j = 0; j < length; j++)instead offor (j = 0; j < sizeof(array); j++).
How can I store something in this format: "0xff" to a char array after declaring the array. I'll demonstrate what I mean below. When writing a code such as this, works just fine: ``` int main (void){ unsigned char array[] = {0xff,0xa4}; return 0; } ``` But, what I need is slightly more complicated. I need to assign something such as 0xff to the array after having already declared it. How can I get this to work and obtain the exact same result as in the piece of code above? With the code below I keep receiving the error "multi-character character constant [-Wmultichar]" and "large integer implicitly truncated to unsigned type [-Woverflow]". ``` int main(void){ unsigned char array[2]; array[0] = '0xff'; array[1] = '0xa4'; return 0; } ```
Usearray[0] = '\xff';to set a single char to a hex numerical.Orarray[0] = 0xff;as you did in the first part of your code, successfully.
I'm trying to figure out how to store the fahrenheit table to memory address 0x20 instead of the default 0x0000. I have tried several routes, but so far, nothing that works. The code is in C. ``` #include <avr/io.h> #include <avr/eeprom.h> int main(void) { uint8_t fahrenheit[20] = {32,34,36,37,39,41,43,45,46,48,50,52,54,55,57,59,61,63,64,66}; for(int i = 0; i < 20; i++) { eeprom_write_byte((uint8_t *)i, fahrenheit[i]); } } ```
eeprom_write_byte((uint8_t *)i, fahrenheit[i]);writes a value to addressi. Therefore, to write value starting from 0x0020 as you wish, just do thiseeprom_write_byte((uint8_t *)i+20, fahrenheit[i]);
``` #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main(){ char command[20]; system("dir"); while(1){ printf("\n\n"); scanf("%s", &command); system(command); } return 0; } ``` this is my code, it's a console app written in C and I wanna be able to control the cmd prompt of my computer, whenever I run new command likecd..the path always goes back to where it was before, how do i make it like a process? sorry I'm new to it.
You can't. Thecdcommand in typical command-line interpreters is an internal command, i.e. built into the command interpreter itself. This is because the current directory is a property of the process itself, and a child process (which is whatsystem()creates, in most cases) can't change the current directory of its parent.
How can I add/create a c/c++ OpenSSL static library with specific crypto algorithms? Let's say I don't wantmd5implementation. how do I create a library without md5?
In configure script you can specifyno-<cipher>option, it will build openssl without the cipher that you specified, you can refer to INSTALL file from openssl package ``` no-<cipher> Build without the specified cipher (bf, cast, des, dh, dsa, hmac, md2, md5, mdc2, rc2, rc4, rc5, rsa, sha). The crypto/<cipher> directory can be removed after running "make depend". ```
In GCC the following C code compiles correctly- ``` int i = 7; i = 5i; printf("%d", i); ``` And prints-0. The statementi = 5iclearly makes no sense. Then why on earth the code does not give any compilation error? And whyibecomes0?
This is aGCC extension for representing the imaginary component of complex numbers. The compiler complains if you compile with-pedanticand-Werror:http://ideone.com/PMlZr5.
This question already has answers here:How do malloc() and free() work?(13 answers)Closed6 years ago. I have allocated memory of 100 MB using malloc ``` block = (char *)malloc(sizeof(10485760)); // char *block is a global variable ``` and then I assigned value in block to some local variable say localblock ``` char *localblock = block; ``` when I tried to access location after 1 MB and copying string in that location im getting access violation error ``` int si = 1048576; for (int i=0; i < si; ++i) ++localptr; ``` strcpy(localblock,"random_string");<--- im getting error here .please help me
``` block = (char *)malloc(sizeof(10485760)); ``` is allocating only sizeof(int) number of bytes, when you access memory beyond that its will end up accessing invalid memory and program might crash
Consider the following code: ``` pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST); pthread_mutex_t mut; pthread_mutex_init(&mut, &attr); pthread_mutexattr_destroy(&attr); pthread_mutex_lock(&mut); ``` Is this code valid? If the mutex is allowed to contain references to the attribute object it was initialized with, then I suppose I may not callpthread_mutexattr_destroy(&attr)before using the mutex.
Like themanualsay: After a mutex attributes object has been used to initialize one or more mutexes, any function affecting the attributes object (including destruction) shall not affect any previously initialized mutexes. So your code is valid (but don't forget to check the potential error of these functions).
``` #include <pthread.h> pthread_mutex_t* mut; int main() { mut = PTHREAD_MUTEX_INITIALIZER; } ``` The above code spits outerror: expected expression before ‘{’ token. ``` #include <pthread.h> pthread_mutex_t* mut = PTHREAD_MUTEX_INITIALIZER; int main() { } ``` The above code spits out warning: braces around scalar initializer So how am I supposed to initialize a mutex?
It is a type error, you should use:pthread_mutex_tinstead ofpthread_mutex_t*: ``` pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; ``` The reason why compiler complains is that is tries to assign this macro expansion ofPTHREAD_MUTEX_INITIALIZERto apointer: ``` { { 0, 0, 0, 0, 0, __PTHREAD_SPINS, { 0, 0 } } } ``` With the corrected approach, you may pass&muteverywhere you needpthread_mutex_t*.
In GCC the following C code compiles correctly- ``` int i = 7; i = 5i; printf("%d", i); ``` And prints-0. The statementi = 5iclearly makes no sense. Then why on earth the code does not give any compilation error? And whyibecomes0?
This is aGCC extension for representing the imaginary component of complex numbers. The compiler complains if you compile with-pedanticand-Werror:http://ideone.com/PMlZr5.
This question already has answers here:How do malloc() and free() work?(13 answers)Closed6 years ago. I have allocated memory of 100 MB using malloc ``` block = (char *)malloc(sizeof(10485760)); // char *block is a global variable ``` and then I assigned value in block to some local variable say localblock ``` char *localblock = block; ``` when I tried to access location after 1 MB and copying string in that location im getting access violation error ``` int si = 1048576; for (int i=0; i < si; ++i) ++localptr; ``` strcpy(localblock,"random_string");<--- im getting error here .please help me
``` block = (char *)malloc(sizeof(10485760)); ``` is allocating only sizeof(int) number of bytes, when you access memory beyond that its will end up accessing invalid memory and program might crash
Consider the following code: ``` pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST); pthread_mutex_t mut; pthread_mutex_init(&mut, &attr); pthread_mutexattr_destroy(&attr); pthread_mutex_lock(&mut); ``` Is this code valid? If the mutex is allowed to contain references to the attribute object it was initialized with, then I suppose I may not callpthread_mutexattr_destroy(&attr)before using the mutex.
Like themanualsay: After a mutex attributes object has been used to initialize one or more mutexes, any function affecting the attributes object (including destruction) shall not affect any previously initialized mutexes. So your code is valid (but don't forget to check the potential error of these functions).
``` #include <pthread.h> pthread_mutex_t* mut; int main() { mut = PTHREAD_MUTEX_INITIALIZER; } ``` The above code spits outerror: expected expression before ‘{’ token. ``` #include <pthread.h> pthread_mutex_t* mut = PTHREAD_MUTEX_INITIALIZER; int main() { } ``` The above code spits out warning: braces around scalar initializer So how am I supposed to initialize a mutex?
It is a type error, you should use:pthread_mutex_tinstead ofpthread_mutex_t*: ``` pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; ``` The reason why compiler complains is that is tries to assign this macro expansion ofPTHREAD_MUTEX_INITIALIZERto apointer: ``` { { 0, 0, 0, 0, 0, __PTHREAD_SPINS, { 0, 0 } } } ``` With the corrected approach, you may pass&muteverywhere you needpthread_mutex_t*.
This question already has answers here:How do malloc() and free() work?(13 answers)Closed6 years ago. I have allocated memory of 100 MB using malloc ``` block = (char *)malloc(sizeof(10485760)); // char *block is a global variable ``` and then I assigned value in block to some local variable say localblock ``` char *localblock = block; ``` when I tried to access location after 1 MB and copying string in that location im getting access violation error ``` int si = 1048576; for (int i=0; i < si; ++i) ++localptr; ``` strcpy(localblock,"random_string");<--- im getting error here .please help me
``` block = (char *)malloc(sizeof(10485760)); ``` is allocating only sizeof(int) number of bytes, when you access memory beyond that its will end up accessing invalid memory and program might crash
Consider the following code: ``` pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST); pthread_mutex_t mut; pthread_mutex_init(&mut, &attr); pthread_mutexattr_destroy(&attr); pthread_mutex_lock(&mut); ``` Is this code valid? If the mutex is allowed to contain references to the attribute object it was initialized with, then I suppose I may not callpthread_mutexattr_destroy(&attr)before using the mutex.
Like themanualsay: After a mutex attributes object has been used to initialize one or more mutexes, any function affecting the attributes object (including destruction) shall not affect any previously initialized mutexes. So your code is valid (but don't forget to check the potential error of these functions).
``` #include <pthread.h> pthread_mutex_t* mut; int main() { mut = PTHREAD_MUTEX_INITIALIZER; } ``` The above code spits outerror: expected expression before ‘{’ token. ``` #include <pthread.h> pthread_mutex_t* mut = PTHREAD_MUTEX_INITIALIZER; int main() { } ``` The above code spits out warning: braces around scalar initializer So how am I supposed to initialize a mutex?
It is a type error, you should use:pthread_mutex_tinstead ofpthread_mutex_t*: ``` pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; ``` The reason why compiler complains is that is tries to assign this macro expansion ofPTHREAD_MUTEX_INITIALIZERto apointer: ``` { { 0, 0, 0, 0, 0, __PTHREAD_SPINS, { 0, 0 } } } ``` With the corrected approach, you may pass&muteverywhere you needpthread_mutex_t*.
I've been under the impression that dynamic memory allocation is slower than static memory allocation, I then read about memory pools, but I'm confused When we compare allocations, we are talking about using malloc vs initializing a variable. But then If one were to allocate a big array with malloc and access it, would we get the same performance as If we allocated it statically? Let's say you had: ``` int i[100]; j = malloc(sizeof(int) * 100); // Would these two lines yield the same performance? i[1] = 10; j[1] = 100; ``` Thank you for reading...
Memory is memory. Once's its allocated, it all behaves the same. Only the allocation is slower.
I want to know number of tokens in the statement given below ``` a+++b---c ``` Please tell me number of tokens I told my viva teacher that there are 7 tokens but he said it is wrong.
You are correct. There are seven tokens: (in C) ``` a ++ + b -- - c ```
Let's say I have a pointer insidefunction1, I need to pass it tofunction2, andfunction2needs to pass it tofunction3,function3needs to update that pointer. How do you correctly do this? Do you use triple stars? If so, what's the correct way to pass the pointer insidefunction2? ``` function1(void){ char *pointer; function2(&pointer) } function2(char **pointer){ function3(&(*pointer)); } function3(char ***pointer)} /*update pointer*/ } ``` My question is specifically about this situation only (3 functions), I don't want to removefunction2, even if it does nothing.
Just keep two levels of pointer. ``` #include <stdio.h> static int b = 42; void foo(int **a) { *a = &b; } void bar(int **a) { foo(a); printf("%d\n", **a); **a = 21; } int main() { int *a = NULL; bar(&a); printf("%d\n", *a); } ``` Output: ``` 42 21 ```
I want to replace the sign"%.4d"with a number (like inprintffunction) in mychar*var For example: ``` printf("| %.4d |", 2); ``` That will print :| 0002 | I tried something like this: ``` int num = 2; //local var for the example char *number = "| %.4d |", num; write(1,number,strlen(number)); ``` But that prints:| %.4d |(not surprising...) note: This part is inside a sighandler, so I cant useprintf
Usesprintf ``` sprintf (number, "| %.4d |", num); ``` Herethe documentation
I was wondering why I have to use malloc to dynamically create memories, while I already have pointer addition to freely manipulate the memories. So I created this code, but this code corrupts, saying that 'stack around the variable 'a' was corrupted' Can someone explain why this code fails? ``` #include <stdio.h> int main(void) { int a = 1; int * arr1 = &a; *(arr1 + 1) = 2; printf("%d %d\n", *arr1, *(arr1+1)); } ```
You have no idea what the implementation might be storing at&a + 1. It might be critical information needed to maintain the sanity of the operating environment. Despite having no idea what it might be used for, you modify it. So anything can happen. Don't write to memory that doesn't belong to you!
int main(int argc, char **argv) { float *rainfall; float rain_today; // rainfall has been dynamically allocated space for a floating point number. // Both rainfall and rain_today have been initialized in hidden code. // Assign the amount in rain_today to the space rainfall points to. return 0; } Hi everyone. This is a really basic question but i havent found a solution yet. Isn't it just ``` rain_today = *rainfall ```
No. rain_today = *rainfall;would take the value pointed byrainfalland put it inrain_today(ideally NULL). What you are being asked to do is putting the value ofrain_todayinto the space pointed by the pointerrainfall which is: ``` *rainfall = rain_today \\the value of rain_toady is COPIED to the space pointed by rainfall ``` Alternatively you could do: ``` rainfall = &rain_today \\rainfall points at the memory location of rain_today ```
I was wondering why I have to use malloc to dynamically create memories, while I already have pointer addition to freely manipulate the memories. So I created this code, but this code corrupts, saying that 'stack around the variable 'a' was corrupted' Can someone explain why this code fails? ``` #include <stdio.h> int main(void) { int a = 1; int * arr1 = &a; *(arr1 + 1) = 2; printf("%d %d\n", *arr1, *(arr1+1)); } ```
You have no idea what the implementation might be storing at&a + 1. It might be critical information needed to maintain the sanity of the operating environment. Despite having no idea what it might be used for, you modify it. So anything can happen. Don't write to memory that doesn't belong to you!
int main(int argc, char **argv) { float *rainfall; float rain_today; // rainfall has been dynamically allocated space for a floating point number. // Both rainfall and rain_today have been initialized in hidden code. // Assign the amount in rain_today to the space rainfall points to. return 0; } Hi everyone. This is a really basic question but i havent found a solution yet. Isn't it just ``` rain_today = *rainfall ```
No. rain_today = *rainfall;would take the value pointed byrainfalland put it inrain_today(ideally NULL). What you are being asked to do is putting the value ofrain_todayinto the space pointed by the pointerrainfall which is: ``` *rainfall = rain_today \\the value of rain_toady is COPIED to the space pointed by rainfall ``` Alternatively you could do: ``` rainfall = &rain_today \\rainfall points at the memory location of rain_today ```
I am trying to write to a file, however, the file pointer is always pointing to NULL as if the file does not exist. The file is in the same directory as the input file, which is found and written to. Any ideas as to why this is happening? ``` FILE *vmoutput = NULL; fopen("vmoutput.txt", "w"); // if file could not be opened return error if(vmoutput == NULL) { printf("FILE COULD NOT BE FOUND\n"); return 1; } ```
How about you fix your code to: store and checkfopen's return valuereport the actual error ? ``` #include <stdio.h> #include <string.h> #include <errno.h> ... FILE *vmoutput = fopen("vmoutput.txt", "w"); if (vmoutput == NULL) { fprintf(stderr, "Can't open %s: %s\n", "vmoutput.txt", strerror(errno)); return 1; } ``` Right now your code always setsvmoutputtoNULL.
I have the following function: ``` void foo(int n){ int i = 0; double temp = 0; for (i = 1; i < n ; i++){ temp = sqrt(i * 1.0); if (temp == (int)temp){ printf("%d ", i); } } } ``` The time complexity is: O(n), is there a way to make the time complexity lower than n?
It looks like this function is searching for perfect squares up ton. Rather than taking the square root of every number up ton, you can instead square every number up tosqrt(n): ``` void foo(int n){ int i = 0; for (i = 1; i*i < n ; i++){ printf("%d ", i*i); } } ``` Not only is this O(sqrt(n)), but it removes floating point operations in thesqrtfunction.
I have a function that creates a string. This is the simple example: ``` char* getString() { char *buffer = (char*)malloc(20 * sizeof(char)); snprintf(buffer, 20, "Some stupid text"); return buffer; } ``` And here is the main function: ``` int main() { printf("%s\n", getString()); return 0; } ``` Is memory leak happening in this code (because Valgrind does not warn about any memory leak)? If it is, how can I avoid this without using new variables in the main function? Thanks
Yes and No you have a memory leak. Yes, you are not explicitly deleting the buffer allocated in your getString function. No, because this leak is occurring within main() with no looping, your buffer is getting deallocated when main () exits. So, while what you are doing is bad coding practice, it is causing no harm in this particular situation. You need to have some variables in main to get around this.
In C language, if we have: ``` typedef int a[100]; typedef int b[200]; ``` Then types a and b are equivalent? As far as I know C uses name equivalence, but I'm very confused.
In your exampleais alias for the typeint[100]andbis an alias for the typeint[200]. These two types are not equivalent as an array's size is part of its type and different sizes mean different types. If the second line weretypedef int b[100];,aandbwould be equivalent. As far as i know C uses name equivalence Structs and unions are nominally typed in the sense that if you have two struct (or union) types tagged A and B, which have exactly the same body, they're still considered different types. So if a variable has typestruct A, you can't assign it astruct Bwithout converting it first. This is not true fortypedefs, which are mere aliases. So if you have two typedefstypedef X a; typedef X b;, thenX,aandbare all indistinguishable from each other.
I have the following function: ``` void foo(int n){ int i = 0; double temp = 0; for (i = 1; i < n ; i++){ temp = sqrt(i * 1.0); if (temp == (int)temp){ printf("%d ", i); } } } ``` The time complexity is: O(n), is there a way to make the time complexity lower than n?
It looks like this function is searching for perfect squares up ton. Rather than taking the square root of every number up ton, you can instead square every number up tosqrt(n): ``` void foo(int n){ int i = 0; for (i = 1; i*i < n ; i++){ printf("%d ", i*i); } } ``` Not only is this O(sqrt(n)), but it removes floating point operations in thesqrtfunction.
I have a function that creates a string. This is the simple example: ``` char* getString() { char *buffer = (char*)malloc(20 * sizeof(char)); snprintf(buffer, 20, "Some stupid text"); return buffer; } ``` And here is the main function: ``` int main() { printf("%s\n", getString()); return 0; } ``` Is memory leak happening in this code (because Valgrind does not warn about any memory leak)? If it is, how can I avoid this without using new variables in the main function? Thanks
Yes and No you have a memory leak. Yes, you are not explicitly deleting the buffer allocated in your getString function. No, because this leak is occurring within main() with no looping, your buffer is getting deallocated when main () exits. So, while what you are doing is bad coding practice, it is causing no harm in this particular situation. You need to have some variables in main to get around this.
In C language, if we have: ``` typedef int a[100]; typedef int b[200]; ``` Then types a and b are equivalent? As far as I know C uses name equivalence, but I'm very confused.
In your exampleais alias for the typeint[100]andbis an alias for the typeint[200]. These two types are not equivalent as an array's size is part of its type and different sizes mean different types. If the second line weretypedef int b[100];,aandbwould be equivalent. As far as i know C uses name equivalence Structs and unions are nominally typed in the sense that if you have two struct (or union) types tagged A and B, which have exactly the same body, they're still considered different types. So if a variable has typestruct A, you can't assign it astruct Bwithout converting it first. This is not true fortypedefs, which are mere aliases. So if you have two typedefstypedef X a; typedef X b;, thenX,aandbare all indistinguishable from each other.
I have a hard time understanding the usage of thrd_join. Its declaration is this: ``` int thrd_join( thrd_t thr, int *res ); ``` The section reads: Ifresis not a null pointer, the result code of the thread is put to the location pointed to byres So I take it that the variablerescontains the return code of the thread to be joined. What is the return value ofthrd_join()used for then? Is that a code signifying that the join will be successful and that I can take contents ofresseriously? Do I have that right?
The thread isstartedwith a function ofthrd_start_twhich is typedef forint(*)(void*)(cf.here), i.e. it takes avoid *, and returns anint. The return value of this function is stored to the location pointed to byres. The return code of the call tothrd_joinitself is its return value.
The below code is not finding '/n' and replacing with '/0'. Looks like the compiler thinks '/n' and '/0' are more than single characters and are expecting integer values. I have tried atoi(), however this did not work. Thanks in advance. ``` for (i=0; i<sizeof(filename); i++){ if (filename[i] == ('/n')) { filename[i]= ('/0'); break; } } createbn.c:35:21: warning: multi-character character constant [-Wmultichar] ^ createbn.c:35:21: warning: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Wint-conversion] ``` On a modern mac, gcc compiler.
You probably meant to use a backward slash to represent the special characters: ``` \0 \n ``` The forward slash does not make it a escape sequence,/0are two characters.
Nonetheless, macros are valuable. One practical example comes from<stdio.h>, in whichgetcharandputcharare often defined as macros to avoid the run-time overhead of a function call per character processed. The functions in<ctype.h>are also usually implemented as macros. This is from the book. I did not understand why MACROS help reducing overhead. All they are doing is to just increase one more step in compilation process.
A macro here is just an old version of inlining a function, automating the process of copy-pasting the function body into every use. Good reading: https://en.wikipedia.org/wiki/Inline_function
so i've created a function that deals with a array of char pointers by using the [] operators. the function ``` int fetchargs(char **argv){ argv[0][0] = 'A'; }; ``` will result in segmentation fault. i pass a array of character pointers that was initialized as follow ``` char argv[ARG_NUM][MAX_LINE]; ``` trying to figure out the cause,but with not success what might be the issuse?
char ** argvis apointer to a pointerof character(s) or adouble pointerWhere asargv[ARG_NUM][MAX_LINE]is essentially a 2D array of characters Bottom line here is to Honor the Data Types ``` char argv[ARG_NUM][MAX_LINE]; ......... ......... int fetchargs(char argv[][MAX_LINE]){ argv[0][0] = 'A'; return 0; }; ```
I have a hard time understanding the usage of thrd_join. Its declaration is this: ``` int thrd_join( thrd_t thr, int *res ); ``` The section reads: Ifresis not a null pointer, the result code of the thread is put to the location pointed to byres So I take it that the variablerescontains the return code of the thread to be joined. What is the return value ofthrd_join()used for then? Is that a code signifying that the join will be successful and that I can take contents ofresseriously? Do I have that right?
The thread isstartedwith a function ofthrd_start_twhich is typedef forint(*)(void*)(cf.here), i.e. it takes avoid *, and returns anint. The return value of this function is stored to the location pointed to byres. The return code of the call tothrd_joinitself is its return value.
The below code is not finding '/n' and replacing with '/0'. Looks like the compiler thinks '/n' and '/0' are more than single characters and are expecting integer values. I have tried atoi(), however this did not work. Thanks in advance. ``` for (i=0; i<sizeof(filename); i++){ if (filename[i] == ('/n')) { filename[i]= ('/0'); break; } } createbn.c:35:21: warning: multi-character character constant [-Wmultichar] ^ createbn.c:35:21: warning: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Wint-conversion] ``` On a modern mac, gcc compiler.
You probably meant to use a backward slash to represent the special characters: ``` \0 \n ``` The forward slash does not make it a escape sequence,/0are two characters.
What will happen if I call free() with non dynamically allocated pointer as the argument? E.g ``` some_struct foo; function(&foo); void function(some_struct* param){ free(param); } ``` Thanks!
It's against the rules, so just about anything might happen.free()might print an error message. The program might crash with a segmentation violation or other memory access error. The error might be silently ignored. Or the error might lead to corruption of the malloc/free heap such that an error or crash might happen during some later call to malloc or free.
This question already has answers here:how to check if the input is a number or not in C?(10 answers)Check if input is integer type in C(16 answers)Closed6 years ago. I'm trying to check if a number is an integer (num). In the main() - ``` int num, input; printf("Please enter an integer greater than 1:\n"); input = scanf("%d",&num); if ( input != 1 ){ printf("Invalid input!\n"); return 1; } ``` but when the input is not an integer (33.3 for example), the value of "input" is still 1. ``` printf("%d ", input); ``` gives me back 1. The rest of the program works. Just got stuck on this minor thing.
You are going to need to read the input into achar[], (so, noscanf()necessary, you can just dogets()or something similar,) and then check the value yourself, digit by digit, usingisdigit().
Is there some tutorial available for Bullseye code coverage tool. Is it automated? How do we find line coverage using this tool?
Function coverage and decision coverage are supported in Bullseye coverage tool.I dont think line coverage/statement coverage is supported. Please see this link. http://www.bullseye.com/measurementTechnique.html
In the following expression, the result of the left shift operation is assigned to the variablei. ``` int i; i = 7 << 32; printf("i = %d\n",i); ``` In the following expression, the left shift assignment operation is carried. ``` int x = 7; x <<= 32; printf("x = %d\n",x); ``` Both the above expressions gave different results. But it's not the same with the following two expressions. Both of them gave the same result. So what could be the reason for the above expressions to return different values? ``` int a; a = 1 + 1; printf("a = %d\n",a); int b = 1; b += 1; printf("b = %d\n",b); ```
The C standard says: The result isundefinedif the right operand is negative, or greater than or equal to the number of bits in the left expression’s type. So, it isundefined behaviorbecauseintis normally32bits in size, which means that only0through31steps arewell-defined.
I understand the relevance and job of a linker in C, but what is happening in the binary? Does the linker copy the binary, from say, a DLL or does it simply reference this library function in binary to carry out the function?
In the case of a DLL the linker simply places references to the functions in the DLL in the executable code, which will (hopefully) be resolved at run-time. In the case of static linking the linker copies the code from the library into the executable, and everything is resolved at link-time. If you really want the full story about linkers, which few people seem really interested in, take a look athttps://www.amazon.co.uk/Linkers-Kaufmann-Software-Engineering-Programming/dp/1558604960which is an excellent book.
I'm currently reading a book on C pointers and there is an example in the book that confuses me: Suppose we have:int arr_of_int[] = {5,10,15};and we set:int *add_of_arr = arr_of_int; then I know that the "add_of_arr" variable holds the address of:arr_of_int[0];and let's just suppose the address of "add_of_arr" is 500. Now, if I do: "add_of_arr += 3;" then the address of "add_of_arr" is now 512? That's what I'm getting from the book, but shouldn't the address of "add_of_arr" still be 500 and only the address HELD by add_of_arr be 512? What i'm getting from the book is that the address of add_of_arr is changing. This confuses me. I'm thinking it's a mistake but I'm not sure. Thanks!
It is a typo: addressinadd_of_arr is now 512, but the addressofadd_of_addr has not changed.
I need to open the default audio capture device and start recording.libsoxseems to bea nice cross-platform solution. Using the binary frontend, I can justrec test.wavand the default microphone is activated. However, when browsing thedocumentation, no similar functionality exists.This threaddiscusses precisely the same topic as my question, but doesn't seem to have reached a solution. Where could an example of usinglibsoxfor recording from the default audio device be located?
You can record using libsox. Just set the input file to "default" and set the filetype to the audio driver (e.g. coreaudio on mac, alsa or oss on linux) ``` const char* audio_driver = "alsa"; sox_format_t* input = sox_open_read("default", NULL, NULL, audio_driver); ``` Look at someexamplesfor more info on how to structure the rest of the code.
I am solving the assignment problem about thread. It's about sorting random lowercase characters. when it's sorted well, I print out O mark and or not, Print out X. using 2 threads. I need to write code using semaphore, but I do not know how to and where to write sempahore. So once I wrote the code without semaphore. I should add the Sempahore now. but i don't know what part to fix. Could you help me? Do i have to make one more function for semaphore? It's my code in C.
As ThingyWotsit said, do go back to your professor. For the semaphore, think of its concept like a gate. The aforementionedsem_post()will increase the semaphore's counter by 1.sem_wait()will permit a thread passage and decrement the counter by 1;however, if after asem_wait()the counter reaches 0, any othersem_wait()will halt the thread, close the gate untilsem_postis> 1. I hope that aids you in your endeavor.
``` #include<stdio.h> int main(){ int x=5; char A_one[8], A_two[8]; } ``` I think x will be at higher address then A_two and A_one(decreasing).
That is not defined, so it cannot be answered in general. For any specific case you can easily try it by printing out the addresses: ``` printf("x is at %p, A_two at %p and A_one at %p\n", (void *) &x, (void *) &A_two, (void *) &A_one); ``` Note that the C standard does not, for instance, require that these variables are put on a stack.
I need to open the default audio capture device and start recording.libsoxseems to bea nice cross-platform solution. Using the binary frontend, I can justrec test.wavand the default microphone is activated. However, when browsing thedocumentation, no similar functionality exists.This threaddiscusses precisely the same topic as my question, but doesn't seem to have reached a solution. Where could an example of usinglibsoxfor recording from the default audio device be located?
You can record using libsox. Just set the input file to "default" and set the filetype to the audio driver (e.g. coreaudio on mac, alsa or oss on linux) ``` const char* audio_driver = "alsa"; sox_format_t* input = sox_open_read("default", NULL, NULL, audio_driver); ``` Look at someexamplesfor more info on how to structure the rest of the code.
I am solving the assignment problem about thread. It's about sorting random lowercase characters. when it's sorted well, I print out O mark and or not, Print out X. using 2 threads. I need to write code using semaphore, but I do not know how to and where to write sempahore. So once I wrote the code without semaphore. I should add the Sempahore now. but i don't know what part to fix. Could you help me? Do i have to make one more function for semaphore? It's my code in C.
As ThingyWotsit said, do go back to your professor. For the semaphore, think of its concept like a gate. The aforementionedsem_post()will increase the semaphore's counter by 1.sem_wait()will permit a thread passage and decrement the counter by 1;however, if after asem_wait()the counter reaches 0, any othersem_wait()will halt the thread, close the gate untilsem_postis> 1. I hope that aids you in your endeavor.
The following statement is from Dennis Ritchie C book The qualifier signed or unsigned may be applied to char or any integer. unsigned numbers are always positive or zero, and obey the laws of arithmetic modulo 2n, where n is the number of bits in the type. So, for instance, if chars are 8 bits, unsigned char variables have values between 0 and 255, while signed chars have values between -128 and 127 (in a two's complement machine.)Whether plain chars are signed or unsigned is machine-dependent, but printable characters are always positive. Fromthisi got the definition "A printable character is a character that is not a control character". The C library functionint isprint(int c)checks whether the passed character is printable. I did not able to find what are plain chars in C. Where can I find the list of plain chars in c?
It's referring tochartype (as opposed tounsigned charorsigned char).
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed5 years ago.This post was edited and submitted for reviewlast yearand failed to reopen the post:Original close reason(s) were not resolvedImprove this question I want to see how math functions work, likesin,cos,tan, etc... Where can I find the source code? is it available locally or in the net?
fdlibm has pure C implementations of the math functions, with comments that explain the algorithms and give references for them.http://www.netlib.org/fdlibm/
This question already has answers here:Consequences of this buffer overflow?(11 answers)Closed6 years ago. I don't understand why this program is working. ``` char *a; a=(char*)malloc(10*sizeof(char)); strcpy(a,"aaaaaaaaaa"); printf("%s",a); ``` I am allocating only 10 character array with 10th character being the '\0' character. So why it is still printing string with length of more that 10?
You've allocated this much memory: ``` | | | | | | | | | | | 1 2 3 4 5 6 7 8 9 10 ``` You've written this much: ``` |a|a|a|a|a|a|a|a|a|a|\0| 1 2 3 4 5 6 7 8 9 10 11 ``` One too many.This is consideredundefined behavior.Or, inmore colorful terms.(As referenced @John Bollinger in the comments.)
I need to write a Recursion function which takes in integer as input and returns the concatenation of the EVEN digits of the input number, i.e., we should remove the odd digits. for example: Creator(1234); return number: 24. Creator(459876); return number: 486. Well I'm pretty stuck in a dead end. I don't know how to return the right numbers. That's my code I don't even know if I'm in the right way so. My code: ``` int Creator(int n) { if (n == 0) return; if ((n % 10) % 2 != 0) Creator(n / 10); return n % 10; } ```
``` int Creator(int n){ if (n == 0) return 0;//You must always return a value. if (n % 2 != 0) return Creator(n / 10); return Creator(n / 10) * 10 + n % 10;//It is necessary to accumulate the call result. } ```
In a example below, I want to know the call offuncwith a wrong type of argument -vptr, which should be called with anintpointer. ``` void func(int * ptr){ } int main(){ void * vptr; func(vptr); } ``` GCC doesn't warn this type of warnings even with wall option. Is there any other options in gcc, or other programming tricks of finding out those bad manners of codes. Aside that, how about in cpp? EDIT: VTT answered this is valid in C, but invalid in C++ with no other cast keywords likestatic_cast(see the other post in detail).
In C, it's a valid implicit conversion. In C++, such conversion requires at leaststatic_castand causes compile-time error otherwise. You should figure out which language are you actually using.
Confused, Why does this work when I compile, when hold is an integer? ``` char value = 'p'; int hold = value; printf("%c", hold); ```
First, in ``` int hold = value; ``` is performed implicit conversion fromchartoint. Second, in ``` printf("%c", hold); ``` the%cspecifier means something asconvert it tocharand print it as symbol.
I need to write a Recursion function which takes in integer as input and returns the concatenation of the EVEN digits of the input number, i.e., we should remove the odd digits. for example: Creator(1234); return number: 24. Creator(459876); return number: 486. Well I'm pretty stuck in a dead end. I don't know how to return the right numbers. That's my code I don't even know if I'm in the right way so. My code: ``` int Creator(int n) { if (n == 0) return; if ((n % 10) % 2 != 0) Creator(n / 10); return n % 10; } ```
``` int Creator(int n){ if (n == 0) return 0;//You must always return a value. if (n % 2 != 0) return Creator(n / 10); return Creator(n / 10) * 10 + n % 10;//It is necessary to accumulate the call result. } ```
In a example below, I want to know the call offuncwith a wrong type of argument -vptr, which should be called with anintpointer. ``` void func(int * ptr){ } int main(){ void * vptr; func(vptr); } ``` GCC doesn't warn this type of warnings even with wall option. Is there any other options in gcc, or other programming tricks of finding out those bad manners of codes. Aside that, how about in cpp? EDIT: VTT answered this is valid in C, but invalid in C++ with no other cast keywords likestatic_cast(see the other post in detail).
In C, it's a valid implicit conversion. In C++, such conversion requires at leaststatic_castand causes compile-time error otherwise. You should figure out which language are you actually using.
Confused, Why does this work when I compile, when hold is an integer? ``` char value = 'p'; int hold = value; printf("%c", hold); ```
First, in ``` int hold = value; ``` is performed implicit conversion fromchartoint. Second, in ``` printf("%c", hold); ``` the%cspecifier means something asconvert it tocharand print it as symbol.
``` #include <unistd.h> #include <stdio.h> int main(){ fork(); return 0; } ``` In my understanding, fork() will copy the parent's process, and run it as a child process; if that was the case, would the program above break? Because how I am understanding this program is: the program above will call fork() indefinitely, and eventually cause a Stack Overflow.
According to the POSIX specification: Both processes shall continue to execute from thefork()function. So, both processes will continue after the call tofork(), and both will immediately terminate.
Confused, Why does this work when I compile, when hold is an integer? ``` char value = 'p'; int hold = value; printf("%c", hold); ```
First, in ``` int hold = value; ``` is performed implicit conversion fromchartoint. Second, in ``` printf("%c", hold); ``` the%cspecifier means something asconvert it tocharand print it as symbol.
``` #include <unistd.h> #include <stdio.h> int main(){ fork(); return 0; } ``` In my understanding, fork() will copy the parent's process, and run it as a child process; if that was the case, would the program above break? Because how I am understanding this program is: the program above will call fork() indefinitely, and eventually cause a Stack Overflow.
According to the POSIX specification: Both processes shall continue to execute from thefork()function. So, both processes will continue after the call tofork(), and both will immediately terminate.
I found this c99 code. Can someone explain what's really happening in here? ``` for(char const * i = "*****";printf("%s\n",i + 4) < 6;i--); ```
Let me dissect that line: ``` for(char const * i = "*****";printf("%s\n",i + 4) < 6;i--); ``` First part of theforloop condition:char const * i = "*****";is just a pointer to 5 star characters.i+1would point to****,i+2would point to***and so on. The second part prints the given number of stars:printf("%s\n",i + 4).Typically in this part of theforloop, we use something likei < n. Here, instead ofiwe get result ofprintf. Take a look atman 3 printfto understand it: RETURN VALUE Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings). So basically we printf the smaller parts of theistring until printf returns6as the number of characters printed.
I basically want to know what to put in the lastprintfstatement for the first%d, because from my understandinggetcharconverts the inputted character to ASCII code. So how do I display the inputted character? ``` #include <stdio.h> int main(void) { int c; printf("Enter a character: "); c = getchar(); printf("The ASCII code for the character %d is %d\n", what to put here, c); return 0; } ```
You need to provide the%cformat specifierin theformat stringinstead of%d: ``` printf("The ASCII code for the character %c is %d\n", c, c); ```
I input Ctrl - D (EOF) when called scanf(), then next scanf ignored. ``` #include <stdio.h> int main() { int input; scanf("%d", &input);//I press Ctrl-D when this line scanf("%d", &input);//this line just passed. not read my input. why? return 0; } ``` I want get input with scanf() second called. What's is a problem?
it seems that your code is OK. The only think is to remember to press "return" at the end of both input number. I rewrite your code in a "better" way: ``` #include <stdio.h> int main(){ int input1,input2; printf("Digit the first number: "); scanf("%i", &input1);//Press return at the end printf("Digit the second number: "); scanf("%i", &input2);//Press return at the end printf("input1:%i\tinput2:%i\n",input1,input2); return 0; } ```
I want to sum two strings and get an int value as result. Why can't I simply subtract 48 to turn a char into an int value? ``` int AddOperator(char *a, char *b){ int sum = 0; char i, j; if (strlen(a) >= strlen(b)){ for(i=0, j=0; i < strlen(a); i++, j++) sum += a[i-48]+b[j-48]; } else if (strlen(b) > strlen(a)){ for(i=0, j=0; i < strlen(b); i++, j++) sum += a[i-48]+b[j-48]; } return sum; ```
Do ``` a[i] - '0'. ``` Also, in the first loop, where length ofais more then length ofb, you will read values frombthat don't exist. Similar situation in second loop however fora.
I'm studying code C on Linux. I have a program to execute a command line which is typed from keyboard. This is my code ``` char* command; scanf("%s", command); execl("/bin/sh", "sh", "-c", command, NULL); ``` and it print out nothing. But the weird thing is: If a do not enter the command line from keyboard anymore and I assign value for the variable, then it work like this: ``` char* command; command = "ls -l"; execl("/bin/sh", "sh", "-c", command, NULL); ``` Can anyone show me why my code doesn't work withscanf() Thanks a lot!
``` char* command; scanf("%s", command); ``` memory is not allocated to command when scanf is being called so its leading to undefined behaviour, you should allocate memory by either ``` command = malloc(256); ``` or declare it as ``` char command[256]; ```
I want to sum two strings and get an int value as result. Why can't I simply subtract 48 to turn a char into an int value? ``` int AddOperator(char *a, char *b){ int sum = 0; char i, j; if (strlen(a) >= strlen(b)){ for(i=0, j=0; i < strlen(a); i++, j++) sum += a[i-48]+b[j-48]; } else if (strlen(b) > strlen(a)){ for(i=0, j=0; i < strlen(b); i++, j++) sum += a[i-48]+b[j-48]; } return sum; ```
Do ``` a[i] - '0'. ``` Also, in the first loop, where length ofais more then length ofb, you will read values frombthat don't exist. Similar situation in second loop however fora.
I'm studying code C on Linux. I have a program to execute a command line which is typed from keyboard. This is my code ``` char* command; scanf("%s", command); execl("/bin/sh", "sh", "-c", command, NULL); ``` and it print out nothing. But the weird thing is: If a do not enter the command line from keyboard anymore and I assign value for the variable, then it work like this: ``` char* command; command = "ls -l"; execl("/bin/sh", "sh", "-c", command, NULL); ``` Can anyone show me why my code doesn't work withscanf() Thanks a lot!
``` char* command; scanf("%s", command); ``` memory is not allocated to command when scanf is being called so its leading to undefined behaviour, you should allocate memory by either ``` command = malloc(256); ``` or declare it as ``` char command[256]; ```
I'd like to know if freeing your whole program upon exit is a good practice or not. Of course I know memory is reclaimed by the system anyway. Here, I'd like to know if quite experienced C developers tend to encourage such practice or not. Thanks.
You shouldalwaysclean up your memory. Don't rely on an operating system to do it. Going forward, you might find your program being part of an environment where the memory isnotfreed for you, and retro-fitting such code could prove tricky.
I would like to get this result : ``` static uint32_t const m_deadbeef = 0x4c414c41 ; //this hex is "LALA" ``` from this input : ``` char data[]="LALA"; ``` So I need to putdatainside theunint32_tso it looks like the first line. How would I do it efficiently ?
This is trivial, you just need to grab the character values and combine them: ``` uint32_t uint_from_string(const char *s) { uint32_t x = 0; for (int i = 0; *s != '\0' && i < 4; ++i) { x <<= 8; x |= (uint32_t) *s++; } return x; } ``` If you use this like so: ``` const uint32_t m_deadbeef = uint_from_string("LALA"); ``` you will get the value0x4c414c41in there. Also,please notethat there is no "putting as hex" going on here, the number just as well be printed in decimal (it's1279347777). Numbers are not in hex, only their representation when printed out.
Is the following code safe to use? I mean if the pattern might be scanned and overwriten in one loop, or if such collision never occurs, or if it is implementation dependent. ``` char pattern[32] = "%31s"; sscanf("hello",pattern,pattern); ``` I didn't find any note about thatherenorhere. (Use case: sometimes I usepatternas temporary buffer.)
The C11 standard (ISO/IEC 9899:2011) covers this. It says: 7.21.6.7 Thesscanffunctionint sscanf(const char * restrict s, const char * restrict format, ...); Therestrictmeans that the format can't be the same as any of the arguments. The description says: If copying takes place between objects that overlap, the behavior is undefined. What you're trying to do is 'undefined behaviour'. Don't do that.
Suppose I define a matrix and assign the value in the following way: ``` double A[row * column]; for (int j = 0; j < column; j++){ for (int i = 0; i < row; i++){ A[j*row + i] = ((double)rand())/RAND_MAX; // random value } } ``` How can I compute the transpose of this matrix? I have tried the following but the resulting matrix is not correct. ``` double B[column * row]; for(int j = 0; j < row; j++){ for(int i = 0; i < column; i++){ B[j*row + i] = A[i*row + j]; } } ```
The indexing should be done in the following way. ``` double B[column * row]; for (int j = 0; j < row; j++){ for (int i = 0; i < column; i++){ B[j*column + i] = A[i*row + j]; } } ```
Create a code that allows people to learn about exponents. The task is to write a code which takes an integer number as an input and returns the values ranging from that of 2(two) raised to power 0(zero) to 2(two) raised to power n(the number specified in input). Input Input contains the number 'n' for which all the values are returned from power of 2 from 0 to n. Output Output contains the values ranging from 2(two) raised to power 0(zero) to 2(two) raised to power n(input) separated by a comma. Constraints -1000 ≤ n ≤ 1000 Sample Input 5 Sample Output 1,2,4,8,16,32 ``` #include <stdio.h> int main(void){ int n;double p=1; scanf("%d",&n); if(n>0){ for(int i=0;i<n;i++,p*=2) printf("%.0lf,",p); printf("%.0lf",p); } else if(n==0) printf("1"); return 0; } ```
You should take care of negative values of 'n'.
I have to use syslog to log a message on terminal. I found a code on internet but it is not working. code: ``` #include <stdio.h> #include <unistd.h> #include <syslog.h> int main(void) { openlog("slog", LOG_PID|LOG_CONS, LOG_USER); syslog(LOG_INFO, "A different kind of Hello world ... "); closelog(); return 0; } ```
Thanks to all for comments and answers. Now, I am able to print a message on the terminal by using LOG_PERROR option in openlog() function.There is no need of LOG_CONS option to print on console. Thanks to @Cheatah for the help. openlog("slog", LOG_PID|LOG_PERROR, LOG_USER); Thank you.