question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I was studying the book "Data Structure and algorithms made easy" and but I got confused while learning "Comparing Linked Lists and Unrolled Linked list"...
what is overhead?
Why he is only stating 8 bytes of overhead for 100 elements array?
|
Overhead is all the stuff that is not part of the data that you want to store. Like the pointers to the next and previous element.
The block list is a list of arrays. Each array contains a number of elements. In principle your entire list could consist of a single block node with an array of all your elements. So less overhead.
It's a bit confusing that head in LinkedBlock points to a ListNode - it should point to whatever the data is (without the prev and next pointers).
|
Let's assume we have 2 programs written in C, one program allocates memory with malloc and launches the second program passing the address of allocated memory and size as arguments.
Now the question, is it possible for the second program to cast the first argument to a pointer and read/write to that memory. Why, why not?
For the sake of simplicity assume Linux as the underlying OS.
|
No, because on modern operating systems processes running in user mode seeVirtual Memory. The same virtual address will translate to a different physical address or page file location between processes.
Fortunately, most operating systems do have APIs that allow for inter-process communication, so you can research those methods.This questionseems to be a good place to start, since you claim to be working on Linux.
|
I've got an array of unsigned chars that I'd like to output to a file using the C file I/O. What's a good way to do that? Preferably for now, I'd like to output just one unsigned char.
My array of unsigned chars is also non-zero terminated, since the data is coming in binary.
|
I'd suggest to use functionfwriteto write binary data to a file; obviously the solution works for arrays ofSIZE==1as well:
```
int main() {
#define SIZE 10
unsigned char a[SIZE] = {1, 2, 3, 4, 5, 0, 1, 2, 3, 4 };
FILE *f1 = fopen("file.bin", "wb");
if (f1) {
size_t r1 = fwrite(a, sizeof a[0], SIZE, f1);
printf("wrote %zu elements out of %d requested\n", r1, SIZE);
fclose(f1);
}
}
```
|
I'm doing a homework assignment in C and I've run into a little trouble.
After calculating two values, I have to be able to print the highest of two valueswithoutusing logical operators, relational operators, or selection constructs. I've already used calculations that determine the larger of the two values, but I don't know if that is very useful going forward.
I would also like to clarify that I am not printing the maximum value, rather I am supposed to print the maximum option. For example, is option 1 = 2000 and option 2 = 3000, I want to be able to print out "option 2 is the larger one".
I should also say that following with the rest of the assignment this selection is typically only done with mathematical operations+*-%/andpow()
|
I would use the functionfmax. It takes doubles as arguments, so you may have to cast your numbers into doubles.
|
I need a way to implement a doubly linked list using only an array and no pointers in C. There's is a mention of this in Thomas Cormen but I can't think of a way to actually implement it.
|
Instead of using pointers which, in C, are usually numbers that index into the address space, use integer indexes into your array as references to the previous and next members e.g.
```
struct Element
{
int next;
int prev;
// Any data you want for this element in the list
};
struct Element array[MAX_ELEMENTS];
```
Then for the element at indexiin the array, the next element in the list is
```
array[array[i].next]
```
and the previous element is
```
array[array[i].prev]
```
Instead of usingNULLto mean a null pointer, use-1to mean a "null" index.
|
how do I perform a signed right shift in c?
like -25 >> 3.
I tried like this:
10011001 >> 3 == 00010011
But the result is -4.
|
According to the standard 6.5.7p5
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 /2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.
The result is implementation-defined, and you should look up how it is defined there.
Assuming twos complement and signed right shift,-25is11100111, shifting it by 3 will lead to11111100which is-4.
|
I was studying the book "Data Structure and algorithms made easy" and but I got confused while learning "Comparing Linked Lists and Unrolled Linked list"...
what is overhead?
Why he is only stating 8 bytes of overhead for 100 elements array?
|
Overhead is all the stuff that is not part of the data that you want to store. Like the pointers to the next and previous element.
The block list is a list of arrays. Each array contains a number of elements. In principle your entire list could consist of a single block node with an array of all your elements. So less overhead.
It's a bit confusing that head in LinkedBlock points to a ListNode - it should point to whatever the data is (without the prev and next pointers).
|
result of
printf("%d\n", 5.0 + 2);
is 0
but
```
int num = 5.0 + 2;
printf("%d\n", num);
```
is 7
What's the difference between the two?
|
The result of5.0 + 2is7.0and is of typedouble.
The"%d"format is to printint.
Mismatching format specification and argument type leads toundefined behavior.
To print afloatordoublevalue withprintfyou should use the format"%f".
With
```
int num = 5.0 + 2;
```
you convert the result of5.0 + 2into theintvalue7. Then you print theintvalue using the correct format specifier.
|
I'm trying to practice with left child-right sibling representation of a tree and I really can't figure out how to find the number of nodes given a certain height.
```
10
|
2 -> 3 -> 4 -> 5
| |
6 7 -> 8 -> 9
```
For example if I choose height 0 than the function should return 1 (because at height 0 I have just 1 node which is the root, in this case 10), if I choose a height of 1, it should return 4 (4 nodes), if I choose a height of 2, then it should return 4 as well.
|
Recurse:
If the tree is empty, it is 0.If the heightHis0, it is 1 + the number of siblings.Otherwise, it is the sum of the nodes at heightH-1in the child and at heightHin the siblings.
|
One of member of theWNDCLASSstructure is handle to the class background brush.
From description:
This member can be a handle to the physical brush to be used for painting the background, or it can be a color value. A color value must be one of the following standard system colors (the value 1 must be added to the chosen color).
QUESTION:
Why must add 1 to this value?
|
It may be because thehbrBackgroundfield acceptNULLvalue.
It's forRegisterClass()function to make the difference betweenCOLOR_SCROLLBARwhich is0andNULLwhich is an acceptable value.
|
One of member of theWNDCLASSstructure is handle to the class background brush.
From description:
This member can be a handle to the physical brush to be used for painting the background, or it can be a color value. A color value must be one of the following standard system colors (the value 1 must be added to the chosen color).
QUESTION:
Why must add 1 to this value?
|
It may be because thehbrBackgroundfield acceptNULLvalue.
It's forRegisterClass()function to make the difference betweenCOLOR_SCROLLBARwhich is0andNULLwhich is an acceptable value.
|
Consider the given 2d array allocation:
```
int (*some)[10] = malloc(sizeof(int[10][10]));
```
This allocates a 10 x 10 2d array. Apparently its type isint (*)[10]. I want to write a functioninitialize()that will allocate it, initialize it and then return a pointer to the array, so that the constructionsome[i][j]would be usable in other functions which can pass a pointer to the array it onto each other.
What should the prototype, specifically the return type ofinitialize()be?
|
```
int (*initialize(void))[10] { ... }
```
initializeis a function, which takes no parameters and returns a pointer to an array of10int.
You should use atypedeffor that.
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed4 years ago.Improve this question
I am writing a socket programming in C to transfer files from Server to Client. where client sends a filename to server and the server reply with the file content. I couldn't understand how a server can intimate the client when the file asked by the client is not found in server side. Do i have to use any standard to reply a package to client, where the client can understand that as a FileNotFound ?
|
In your communication model, you are missing a layer of meta-data or control messages. at the minimum, you need to pass a status code before you return the file. I suggest that you implement a simplified version of HTTP client. you can find an example at:
GitHub - reagent/http: Simple HTTP client in C
|
I am trying to send/receive data with J1939 protocol. So in PIC18F26K83 there are 3 modes for can bus Mode 0: Legacy, Mode 1: Enhanced Legacy and Mode 2: FIFO. I want to use 29 bit extended identifier messages but I am not sure if i can use Mode 0 for this operation. In datasheet it is not really clear and in some lines it says something like extended identifiers are not supported in Mode 0. To sum up can I use extended ID's in Mode 0( legacy mode) for PIC18F26K83? Thanks.
|
I can not see why you can't use 29 bits identifiers in Mode 0. Literally, I can't see in the datasheet where it says anything about it.
Besides, what it does say is that Mode 0 is made to be fully compatible with PICs like 18Fxx8, which are actually compatible with 29 bits identifiers.
|
This question already has answers here:What does "%3d" mean in a printf statement?(8 answers)Closed4 years ago.
can someone explain what the 25 in front of d does in an printf command ?
I have searched the web but don't find a good answer.
e.g.:
printf("%-30s %10lu %25d - %ud\n", "unsigned int", sizeof(unsigned int), 0, UINT_MAX);
Thanks in advance.
|
%d indicates decimal value.25 total field width.
|
I am new to the C programming language and I am trying to understand the intent of a function which takes a pointer argument but uses the address of operator on it as though it was a variable name in the function's body? The parameters being passed are of type struct. In other words, why did the author choose to use &lib -> fatfs; instead of lib->fatfs? Is the "address of" operator used to ensure that a null pointer is not being passed?
```
void SDCardLib_init(SDCardLib * lib, SDCardLib_Interface * interface)
{
lib->interface = interface;
f_mount(0, &lib->fatfs);
disk_initCallBack(interface);
}
```
|
The address-of operator is not being applied to the pointerlibbut to thefatfsmember of the pointed to object. The->operator has higher precedence then the unary&operator.
That means that&lib->fatfsis the same as&(lib->fatfs). This should make it more clear what&is taking the address of.
|
I am trying to convert NV12 raw data to H264 using hw encoder of FFMPEG.
to pass raw data to encoder I am passing AVFrame struct using below logic:
```
uint8_t * buf;
buf = (uint8_t *)dequeue();
frame->data[0] = buf;
frame->data[1] = buf + size;
frame->data[2] = buf + size;
frame->pts = frameCount;
frameCount++;
```
but using this logic, I am getting, color mismatched H264 data,
Can someone tell me , How to pass buffer to AVFrame data?
Thanks in Advance,
Harshil
|
I solved color mismatch issue by passing correct linesize and data value of AVFrame struct.
Let's say NV12 has YYYYUVUV plane for 4x4 image, then in ffmpeg, we need to pass
linesize[0] = start location of y
linesize[1] = 4 because location of u started at 4
and we dont need to specify linesize[2] because uv are packed.
and also in case of data
data[0] = start location of y
data[1] = 4
|
I am trying to send/receive data with J1939 protocol. So in PIC18F26K83 there are 3 modes for can bus Mode 0: Legacy, Mode 1: Enhanced Legacy and Mode 2: FIFO. I want to use 29 bit extended identifier messages but I am not sure if i can use Mode 0 for this operation. In datasheet it is not really clear and in some lines it says something like extended identifiers are not supported in Mode 0. To sum up can I use extended ID's in Mode 0( legacy mode) for PIC18F26K83? Thanks.
|
I can not see why you can't use 29 bits identifiers in Mode 0. Literally, I can't see in the datasheet where it says anything about it.
Besides, what it does say is that Mode 0 is made to be fully compatible with PICs like 18Fxx8, which are actually compatible with 29 bits identifiers.
|
This question already has answers here:What does "%3d" mean in a printf statement?(8 answers)Closed4 years ago.
can someone explain what the 25 in front of d does in an printf command ?
I have searched the web but don't find a good answer.
e.g.:
printf("%-30s %10lu %25d - %ud\n", "unsigned int", sizeof(unsigned int), 0, UINT_MAX);
Thanks in advance.
|
%d indicates decimal value.25 total field width.
|
Hi I am working on a monty hall generator and in part of my code I need it to generate random number 2 or 3. It cannot be 1,2,3 but the computer needs to select between 2 or 3.
Thanks!
I have triedrandomCarDoor = ( rand() % 3 ) + 1;but does not work.
randomCarDoor = ( rand() % 3 ) + 1;
It gives me the number1,2,3but I just want2and3
|
You can use the low order bit of the random value, but it is very risky as some pseudo-random number generators do not provide adequate dispersion on low order bits:
```
int two_or_three = 2 + rand() % 2;
```
A much better way is to use the magnitude of the random number which is specified as having a flat distribution:
```
int two_or_three = 2 + (rand() >= RAND_MAX / 2);
```
If you want numbers1and3, here is a simple solution for any pair:
```
int random_value = (rand() < RAND_MAX / 2) ? 1 : 3;
```
|
I need a Raspberry Pi - which I am coding in C - to be able to communicate with an HTTP server, similar to how a dynamic web page can use AJAX to interact with its origin server.
How do I do that? Do I callsystem()with a URL as parameter?
Or it there some other way to do it?
|
The very simplest way would be to use asystem()call with curl. For example:
```
#include <stdlib.h>
int main() {
system("curl http://example.com/");
}
```
This will send aGETrequest to example.com and print the output. Depending on your application, that might be enough. (See themanpagefor more options.)
However, actually capturing the output and doing error handling will be more difficult than if you'd used a C library like curl.
Here's an example of how to use curl-the-library:https://curl.haxx.se/libcurl/c/simple.html
|
This question already has answers here:Resize an Array while keeping current elements in Java?(12 answers)Closed4 years ago.
I don't know how should I type the new resized array.
I create this in C...
```
void main()
{
int=1;
int h[a];
a++;
h[a];
h[1]=2;
printf("%d",h[1]);
}
```
|
You can't do it like that. If you want to dynamically change the size of the array, you would have to usenewoperator. You have allocate a new array with higher size and then copy all the old elements. Something like below.
```
int sz = 1;
int[] h = new int[sz];
sz++;
int h1 = new int[sz];
for (int i = 0; i < h.length;++i) {
h1[i] = h[i];
}
h = h1;
h[1]=2;
printf("%d",h[1]);
```
|
This question already has answers here:What can happen if printf is called with a wrong format string?(5 answers)Closed4 years ago.
Below is the C program and the output is 201. I have no idea how this is possible. Please explain this.
```
#include <stdio.h>
int main() {
int number = 288;
char * ptr;
ptr = (char * ) & number;
printf("%x", * ptr);
ptr++;
printf("%x", * ptr);
return 0;
}
```
This is in case of little endian machine. This question was asked in the MCQ contest on geeksforgeeks. But they provided no explaination of it.
|
The 201 is perfectly reasonable (on little-endian systems):
The variablenumberstarts with these two bytes (on little-endian systems): 0x20, 0x01.
|
I tried to compile a.cfile but it returns the error:
```
yay.c:6:19: fatal error: netdb.h: No such file or directory
#include <netdb.h>
^
compilation terminated.
```
I did some research and apparently.his a header file for C...
I am new to C so I don't know what to do.
|
Dolocate netdb.hunderunixto find out (the filepath).
Underopenbsdit is in located at/usr/include/netdb.h(installed with thecompXXfile set, and not being packaged asglibc)
cheaders are usually placed in/usr/includeand/usr/local/includedirectories depending on if they are system or local (third-party, custom), respectively.
|
---EDIT--- The array was previously initialized as a pointer (*arr).
For a problem I´m trying to solve, I need to go through an array of variable size and started using this loop:
```
int arr[] = {3, 5, 10, -2, -1, -3}; // Just an example
int i = 0;
while(arr[i]) {
//do something
i++;
}
```
It seems that after going through the array I initiliazed, the code finds some random values stored in memory and keeps counting, even though the array I´m trying to work with has long been passed.
How could I avoid this?
Best regards!
|
int *arris not the array.
intis not the type which should be used as the index. Usesize_tinstead
Array
int arr[50];<- this the array
you can get the size of the array dividing its size by the size of the element.
pointer
int *ptr;it only references the int object. Youcantget the size of the allocated memory by dividing size of the pointer by size of reference object
|
This question already has answers here:Resize an Array while keeping current elements in Java?(12 answers)Closed4 years ago.
I don't know how should I type the new resized array.
I create this in C...
```
void main()
{
int=1;
int h[a];
a++;
h[a];
h[1]=2;
printf("%d",h[1]);
}
```
|
You can't do it like that. If you want to dynamically change the size of the array, you would have to usenewoperator. You have allocate a new array with higher size and then copy all the old elements. Something like below.
```
int sz = 1;
int[] h = new int[sz];
sz++;
int h1 = new int[sz];
for (int i = 0; i < h.length;++i) {
h1[i] = h[i];
}
h = h1;
h[1]=2;
printf("%d",h[1]);
```
|
This question already has answers here:What can happen if printf is called with a wrong format string?(5 answers)Closed4 years ago.
Below is the C program and the output is 201. I have no idea how this is possible. Please explain this.
```
#include <stdio.h>
int main() {
int number = 288;
char * ptr;
ptr = (char * ) & number;
printf("%x", * ptr);
ptr++;
printf("%x", * ptr);
return 0;
}
```
This is in case of little endian machine. This question was asked in the MCQ contest on geeksforgeeks. But they provided no explaination of it.
|
The 201 is perfectly reasonable (on little-endian systems):
The variablenumberstarts with these two bytes (on little-endian systems): 0x20, 0x01.
|
I tried to compile a.cfile but it returns the error:
```
yay.c:6:19: fatal error: netdb.h: No such file or directory
#include <netdb.h>
^
compilation terminated.
```
I did some research and apparently.his a header file for C...
I am new to C so I don't know what to do.
|
Dolocate netdb.hunderunixto find out (the filepath).
Underopenbsdit is in located at/usr/include/netdb.h(installed with thecompXXfile set, and not being packaged asglibc)
cheaders are usually placed in/usr/includeand/usr/local/includedirectories depending on if they are system or local (third-party, custom), respectively.
|
I have following struct defined which I can not change:
```
typedef struct _content {
int length;
char **lines;
} content_t;
```
I initialized it in the main function like that:
```
struct _content cont;
cont.length = 6;
cont.lines[cont.length-1][255];
```
I try to assign a value to a certain element of the multidimensional array and also
to print the value out- which doesn't work:
```
cont.lines[1][1] = "A";
printf("\n\n%c", cont.lines[1][1]);
```
What am I doing wrong here?
Many Thanks
|
```
int main(){
content_t cont;
cont.length = 6;
cont.lines=malloc(sizeof(char*)*cont.length);
for(int i=0;i<cont.length;i++) cont.lines[i]=malloc(255);
printf("\n\n%c", cont.lines[1][1]);
for(int i=0;i<cont.length;i++) free(cont.lines[i]);
free(cont.lines);
}
```
that's the right way to do it
|
I have a MIDI controller with several knobs. Is it possible to query state of all values, which these knobs have, when I connect to the device usingmidiInOpenfunction without physically moving each of them?
|
There is no standard MIDI message to inquire about the current state of a controller; messages are sent only when something changes.
Unless your controller has a vendor-specific extension that does exactly what you want, this is not possible.
|
I want to print function names (imported, exported, normal/local functions) but not variable names and so on.
SymEnumSymbolsExenumerates all symbols, but I only want functions.
Also can not find how to distinguish functions and variables insidecallbackfunction.
Is there a way to enumerate only functions?
|
SYMBOL_INFOpassed to your callback hasFlags, and there isSYMFLAG_FUNCTIONfor functions
|
I have to create a function
void destroy(int ***matrix); use to deallocate the matrix
And i dont know how can i deallocate it without knowing its sizes
I'd some ideas or an example of a code.
|
You have to have a convention that only pointers before a sentinel value (e.g.NULL) need to be freed.
```
void destroy (int ***matrix) {
if (matrix == NULL) return;
for (int i = 0; matrix[i]; ++i) {
for (int j = 0; matrix[i][j]; ++j) {
free(matrix[i][j]);
}
free(matrix[i]);
}
free(matrix);
}
```
|
While i was creating my own malloc, I used write to print some value.
I don't have any problems to print value, I just create a char variable to stock my number and print it, but I don't understand why the cast doesn't work.
The prototype of write is:
ssize_t write(int fd, const void *buf, size_t count)
So i cast my number in void * without any result.
```
int nb = 3;
char numb = nb + '0';
write(1, (void *)(nb + '0'), 1); // Display nothing
write(1, &numb, 1); // Display 3
```
Someone can explain why the first write display nothing?
|
Yes, but it's not acast, it's acompound literal:
```
write(1, (char[]){nb + '0'}, 1);
```
or:
```
write(1, &(char){nb + '0'}, 1);
```
|
I am looking for a simple answer to a simple question but I have yet to find a straight forward answer.
For the Hamming code sequence (7 4), it can either do 1-bit detection and correction or 2-bit error detection.
I would like to know the same thing for the (255 247) Hamming sequence. If there is an algorithm to work this out I would very much appreciate it as I am interested in knowing this information for the other Hamming sequences.
Is there also perhaps a C code example for (255 247) encoding exclusively?
|
Theminimum hamming distancedetermines the error detection/correction capabilities of a code.
Hamming codes(eg.Hamming(7,4)or Hamming(255,247)) have a hamming distance of 3 (d = 3), so can detect 2-bit errors (d - 1 = 2) or correct 1-bit errors ((d - 1) / 2 = 1).
|
by checking the serial folder @:
\drivers\tty\serial
There are many different serial port drivers there, which one is for x86?
|
There is no single UART chip for x86.The IBM PC originally used the8250, later it began customary to replace it with the16550and later with the 16750.With the advent ofSuperIO chipseach manufacturer had their implementation of the UART but all were more or less compatible with the 16550/750 and the 8250.Today chipsets usually have one ore more 16750 UARTs integrated in the PCH but they don't have an external socket, so a lot of USB/PCI third-party serials are present in the market.In the end, the driver depends on the UART chip.
If you are interested in the integrated UART (with the socket on the back of your PC), the driver is probably in the8250 folderunless your chipset uses a different UART chip.
|
I have two numbers of char type say
```
char* N1;
char* N2;
N1 = "92345610172222";
N2 = "12351097654671";
```
I need to add MSD's of two numbers i.e
9 + 1 = 10
I solved by typecasting and dividing the number until it encounters a single digit using two loops.Sum it and return the result.
```
int sumMsd(char *N1, char *N2) {
int one = (int)*N1;
int two = (int)*N2;
while (one >= 10)
one /= 10;
while (two >= 10)
two /= 10;
return one+two;
}
```
The logic fails when int size is very large. So,I need to optimize my solution without using library functions. I am looking out for a solution in C.
|
This should work.
```
int sumMsd(char *N1, char *N2) {
return (N1[0] - '0') + (N2[0] - '0');
}
```
Let the first digit of N1 be '3'. Then '3' - '0' is 3, the difference between their ASCII values.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed4 years ago.Improve this question
I want to assign integer value to character.Where 'C' has the least and 'B' largest value.
Is there something better than mapping ?
For eg:-'C'=100,'D'=101,'E'=102....'B'=126.Is There any better way compared to mapping ?
If Input string is "BYE",Ouput should be 351 (Because 'B'=126,'Y'=123,E='102').
|
You can use designated array initializers:
```
// UCHAR_MAX is from header <limits.h>
int const map[UCHAR_MAX] = {
['C'] = 100,
['D'] = 101,
['B'] = 126,
};
```
Unassigned characters will have zero value.
You would then get single value with expression:
```
int value = map[(unsigned char)character];
```
|
```
short int cipher[50],len;
while(cipher != 0)
{
cipher=cipher/10;
++len;
}
```
Need to count number of digits provided by user.
```
error: invalid operands to binary / (have ‘short int *’ and ‘int’)
cipher=cipher/10;
```
|
As gsamaras noted, you definedcipheras an array of 50short ints. Presumably you want only one number, so you'd define it e. g. aslong long cipher;(C is not COBOL or something where one has to specify the number of digits). And don't forget to initializelen.
|
I have a question i came across embedded software development. I can programme gui and flash Arm Cortex m3/m4 proceesors with spi I2c uart bus interfaces. I can make decent gui on it using libraries like qt or emwin.
My question is can i flash android tablet with my own gui on it. I mean i dont want android os on my tablet. Can i flash my own custom firmware on android tablet. Where do i get the schematic of those tablets and is there any project on web like this.
Please dont put comments like why you want to do it. My question is simple can i / we do it if yes than how please.
Thank You !!!
|
The closest you can get is runningPostmarketOS, which is Linux Distribution with GNU userland for Android Devices.
Developing a custom firmware is hardwork. Checkout the PostmarketOS website for the list of devices Compatible.
|
I am using a tool that has been written in C or C++.
https://github.com/kern-lab/discoal
I've never used C myself. In one of the files in discoal.h, I want to change:#define MAXSITES 220020to#define MAXSITES 1100000. The tool manual says that I would have change the MAXSITES define in discoal.h and then recompile. How do I recompile?
I have never used C language before and I am not a Computer science student therefore, do not have much experience in programming either. Therefore, if you could let me know the command to recompile that'll be great. I've provided a link to that tool in case you want to look at the files.
|
Open a terminal, cd to the directory where the Makefile is, and typemake, then hit Enter.
Prerequisites: A C compiler, which comes with Xcode on a Mac, as @Shawn commented.
|
I made the core dumped error with the two pieces of codes below:
```
//test.cpp
int main()
{
int *p = new int;
*p = 100;
delete p;
delete p;
return 0;
}
//test2.cpp
int main()
{
int *p = new int;
*p = 100;
delete p;
*p = 111;
std::cout<<*p<<std::endl;
return 0;
}
```
Gdb told me that the first piece of code got core dumped because of the signal SIGABRT, whereas the second piece of code got core dumped because of the signal SIGSEGV.
Could you tell what is the difference?
|
The SIGABRT isexplicitly detected and signaledby the implementation ofdeletewhose detected the invalidity of the second delete. It is launch by calling theabortfunction
The SIGSEGV is different, it isundergoingrather than detected by a check in a library like the previous, it is launch through the memory management of the OS
seehttps://en.cppreference.com/w/c/program/SIG_types
|
I'm trying to build libjpeg-turbo from source to include 12 bit support. I downloaded the source code fromhere(2.0.1) then followed instruction given in Building.md
```
cd libjpeg-turbo-2.0.1
mkdir build && cd build
cmake -G"Unix Makefiles" -D WITH_12BIT=1 -D WITH_TURBOJPEG=1 ..
make -j8
sudo make install
```
The compilation is successful and generates onlylibjpeg.so,libjpeg.so.62andlibjpeg.so.62.3.0along with bunch of other binary files. But its not building the lib fileslibturbojpeg.so.0.2.0,libturbojpeg.aandlibturbojpeg.sowhich i need. I'm not sure where I am going wrong. i have also tried without the-D WITH_TURBOJPEGflag.
I'm trying this on Ubuntu 16.04 on Nvidia Tx2.
Any help is greatly appreciated.
Thanks
|
Line 201 ofCMakeLists.txtturnsWITH_TURBOJPEGoff when building withWITH_12BITenabled.
Don't enableWITH_12BITand thenWITH_TURBOJPEGwill be default enabled and should build those libraries.
|
Today I had troubles with corrupted heap on ESP32. As it turned out, bug was caused by this line:
```
u8x8_i2c_cmdinfo* cmdinfo = malloc(sizeof(cmdinfo));
```
When I meant
```
u8x8_i2c_cmdinfo* cmdinfo = malloc(sizeof(u8x8_i2c_cmdinfo));
```
It actually surpriszed me a lot that wrong version compiled at all.
Why do it work? What it actually does?
|
The code compiles because variable exists after its declaration. And this part just declared it:u8x8_i2c_cmdinfo* cmdinfo.
You wouldn't be surprised if that worked, right?
```
u8x8_i2c_cmdinfo* cmdinfo;
cmdinfo = malloc(sizeof(cmdinfo));
```
Keep in mind, that while your code compiles fine, it has a nasty bug. You are allocating space for the size of the pointer, most likely not what you want to do.
|
I have a question i came across embedded software development. I can programme gui and flash Arm Cortex m3/m4 proceesors with spi I2c uart bus interfaces. I can make decent gui on it using libraries like qt or emwin.
My question is can i flash android tablet with my own gui on it. I mean i dont want android os on my tablet. Can i flash my own custom firmware on android tablet. Where do i get the schematic of those tablets and is there any project on web like this.
Please dont put comments like why you want to do it. My question is simple can i / we do it if yes than how please.
Thank You !!!
|
The closest you can get is runningPostmarketOS, which is Linux Distribution with GNU userland for Android Devices.
Developing a custom firmware is hardwork. Checkout the PostmarketOS website for the list of devices Compatible.
|
I am using a tool that has been written in C or C++.
https://github.com/kern-lab/discoal
I've never used C myself. In one of the files in discoal.h, I want to change:#define MAXSITES 220020to#define MAXSITES 1100000. The tool manual says that I would have change the MAXSITES define in discoal.h and then recompile. How do I recompile?
I have never used C language before and I am not a Computer science student therefore, do not have much experience in programming either. Therefore, if you could let me know the command to recompile that'll be great. I've provided a link to that tool in case you want to look at the files.
|
Open a terminal, cd to the directory where the Makefile is, and typemake, then hit Enter.
Prerequisites: A C compiler, which comes with Xcode on a Mac, as @Shawn commented.
|
Somewhat of a beginner here.
Ex: 12cx7,14:53:00,0.968900025,0,0,,0,
The end has no value in this case (for this problem the value can be 1-4 but I think the way I read it should be fine)
The way I was thinking of handling it was to handle it the same way I would a double comma (an empty mid value) using strstr to find ",," and strcpy to replace it with a ",-1,". Would I be able to do that with the same setup but with ",/n" and replace with ",-1/n"
|
you can just add an extra ',' at the end of the string to parse, so you will get the last field between the last two ','
if the last field is present you will get it, if it is absent you will get an empty string
|
I would like to use Windows SDK 7.1 to compile some C functions in Matlab r2014b.
Now I wonder which C standard the compiler follows?
My previous research in google (no study of manuals) did not yield a result yet.
Furthermore I would like to know if it is possible to change the used standard.
|
When I run the commandcl.exe /?on the Windows SDK 7.1 Command Prompt, it reports version number16.00.30319.01, which, according to the accepted answer onthis questionis the version of the compiler that ships with Visual Studio 2010.
According toWikipedia, Microsoft did not begin to add support for C99 until Visual Studio 2012, so the compiler that ships with Windows SDK 7.1 must be at most C90-compliant.
|
This question already has answers here:What is E in floating point?(4 answers)Scanf/Printf double variable C(3 answers)Closed4 years ago.
When I run the code below
```
int main(int argc,char *argv[]) {
double n = 2E-1;
printf("%d",n);
}
```
When I run the code it prints a weird number instead of 0.2(2E-1).
|
What does the constant E do in the c language
The documentation for floating-point constants ishere.
The form1e2or1E2means1times ten to the power of2, and you're perfectly correct that2E-1means2times ten to the power of-1, or0.2.
It's based on the scientific E notation linked by Eugene.
When I run the code it prints a weird number
That's just because you used the wrong format specifier. These are documentedhere, and you can see you should use one ofeEfFgGfor doubles.
|
I get an error when the scanf tries to access titolo[i]->nome and I don't get why
```
typedef struct tit *TITOLO;
struct tit {
char nome[20];
};
int main()
{
TITOLO *titolo;
titolo =(TITOLO *) malloc(4*sizeof (TITOLO));
if (titolo == NULL) exit(1);
int i;
for (i=0;i<4;i++) {
printf("Insert title: ");
scanf("%s", titolo[i]->nome);
}
return 0;
}
```
|
typedef struct tit *TITOLO;defines TITOLO as a pointer type, not a struct type. Get rid of this and typedef the struct instead:
```
typedef struct {
char nome[20];
} TITOLO;
TITOLO* titolo = malloc(4*sizeof(*titolo));
```
|
If I run this code:
```
float a=1.123456789;
printf("The float value is %f\n",a);
double b=1.123456789876543
printf("The double value is %lf",b);
```
It prints:
The float value is 1.123457The double value is 1.123457
The first line is understandable since the precision of float is ~6 decimal digits. But shouldn't the 2nd line be displaying more digits? I am using Turbo C++ 4.0 for Windows, if that helps.
|
The%fformat specifier prints 6 digits of precision by default. If you want to print more digits, you need to add a precision to the format specifier:
```
float a=1.123456789;
printf("The float value is %.15f\n",a);
double b=1.123456789876543;
printf("The double value is %.15lf",b);
```
Output:
```
The float value is 1.123456835746765
The double value is 1.123456789876543
```
|
I have multiple files in a directory, ending with the same name *.html.html, I'm looking for a way to get their names and change them to just *.html using therename()function in c or c++ or any other way to solve this problem
|
In command line, simply use:
```
ren *.html.html *.html
```
Or, in PowerShell:
```
Dir *.html.html | rename-item -newname { [io.path]::ChangeExtension($_.name, "html") }
```
Shell would be the simplest option and the most sensate to use. Using C would be overkilling it. Any scripting language (python, php) would be a simpler solution.
If you really really just want to do it in C, you can have a look at this SO question:How do I loop through all files in a folder using C?
|
This question already has answers here:What is E in floating point?(4 answers)Scanf/Printf double variable C(3 answers)Closed4 years ago.
When I run the code below
```
int main(int argc,char *argv[]) {
double n = 2E-1;
printf("%d",n);
}
```
When I run the code it prints a weird number instead of 0.2(2E-1).
|
What does the constant E do in the c language
The documentation for floating-point constants ishere.
The form1e2or1E2means1times ten to the power of2, and you're perfectly correct that2E-1means2times ten to the power of-1, or0.2.
It's based on the scientific E notation linked by Eugene.
When I run the code it prints a weird number
That's just because you used the wrong format specifier. These are documentedhere, and you can see you should use one ofeEfFgGfor doubles.
|
I get an error when the scanf tries to access titolo[i]->nome and I don't get why
```
typedef struct tit *TITOLO;
struct tit {
char nome[20];
};
int main()
{
TITOLO *titolo;
titolo =(TITOLO *) malloc(4*sizeof (TITOLO));
if (titolo == NULL) exit(1);
int i;
for (i=0;i<4;i++) {
printf("Insert title: ");
scanf("%s", titolo[i]->nome);
}
return 0;
}
```
|
typedef struct tit *TITOLO;defines TITOLO as a pointer type, not a struct type. Get rid of this and typedef the struct instead:
```
typedef struct {
char nome[20];
} TITOLO;
TITOLO* titolo = malloc(4*sizeof(*titolo));
```
|
If I run this code:
```
float a=1.123456789;
printf("The float value is %f\n",a);
double b=1.123456789876543
printf("The double value is %lf",b);
```
It prints:
The float value is 1.123457The double value is 1.123457
The first line is understandable since the precision of float is ~6 decimal digits. But shouldn't the 2nd line be displaying more digits? I am using Turbo C++ 4.0 for Windows, if that helps.
|
The%fformat specifier prints 6 digits of precision by default. If you want to print more digits, you need to add a precision to the format specifier:
```
float a=1.123456789;
printf("The float value is %.15f\n",a);
double b=1.123456789876543;
printf("The double value is %.15lf",b);
```
Output:
```
The float value is 1.123456835746765
The double value is 1.123456789876543
```
|
I have multiple files in a directory, ending with the same name *.html.html, I'm looking for a way to get their names and change them to just *.html using therename()function in c or c++ or any other way to solve this problem
|
In command line, simply use:
```
ren *.html.html *.html
```
Or, in PowerShell:
```
Dir *.html.html | rename-item -newname { [io.path]::ChangeExtension($_.name, "html") }
```
Shell would be the simplest option and the most sensate to use. Using C would be overkilling it. Any scripting language (python, php) would be a simpler solution.
If you really really just want to do it in C, you can have a look at this SO question:How do I loop through all files in a folder using C?
|
This question already has answers here:How to store a variable at a specific memory location?(8 answers)Closed4 years ago.
For my embedded systems application, I want to allocate memory from a particular address. I know it can be dangerous but I just want to do it for testing purpose. So If I could point array globally to a particular memory address I can actually allocate array size of memory. I can point integer to a specific memory address like:
```
int *fsp_new_addr = (int*) 0xFF000000;
```
how can I do same thing for array, or is there any alternative way to do this task ?
|
It's exactly the same.fsp_new_addr[1]is the first element after that address.
Of course, as you stated, this can be dangerous, as you are not programmatically allocating memory, but deciding that this bit of memory is going to be a dedicated array for some purpose.
|
I have to input an array of integers. The length of this array is determined at runtime when the user hits some sentinal key (likely I'll use return)
EXAMPLE
```
//input path to be analyzed
int n = 0;
while(scanf("%d",&input[n])==1){
//??
}
}
```
Input:
3 2 1 3 4 5 (return)
Then these values are stored in the array a as:
[3, 2, 1, 3, 4, 5]
I also need proper error checking of course.
This is a basic problem im sure however I'm unable to solve it.
Thanks!
Im thinking ill need a while loop however im unsure how to use scanf to both terminate the loop, initilize the array and input the values.
|
You can do it as follows:
```
int main()
{
char ch;
int i=0;
int input[100000]; //Or dynamically allocate
while(scanf("%c",&ch) && (ch!='\n')){
if(ch==' ') continue;
input[i++]=ch - '0';
printf("%d ",input[(i-1)]);
}
}
```
|
Consider the following code:
```
#include <stdio.h>
#include <inttypes.h>
void main(void)
{
int32_t a = 44;
fprintf(stdout, "%d\n", a);
fprintf(stdout, "%"PRId32"\n", a);
}
```
When is it better to use%dand when would it be better to use"%"PRId32? How do both of those format characters differ? Does this have something to do with howint32_tis typedeffed on your hardware/machine?
|
Use%dforintandPRId32forint32_t.
Maybe on your platformint32_tis just a typedef forintbut this is not true in general.
Using a wrong specifier invokes undefined behavior and should be avoided.
As pointed out by @EricPostpischil note that%dis used inside a quoted format string whilePRId32is used outside. The reason for this is thatPRId32is a macro which expands to a string literal and is then concatenated.
|
DNM_Manager.c
```
struct DNM_s
{
uint32_t Addr;
uint32_t SerialNum;
uint32_t SubnetMask;
uint16_t Tick;
uint8_t Name[NAME_SIZE];
}DNMTemp;
pDNM DNMManager_New(void) //reentrant?
{
return &DNMTemp;
}
```
GeeksForGeekssays: To be reentrant, the function may not use global and static data.
I do use global data "DNMTemp" in this case. However, DNMTemp's value is not changed and function only return its address.
|
Yes.
From the tag excerpt ofreentrancy:
A subroutine is considered reentrant if it can be safely called before a previous call has completed.
In your case, since the function only returns the address of a global (static) variable, which should remain constant after the program starts, the function is well re-entrant.
IMO, reentrant functioncanaccess global and static data,without changing any, so obtaining the address of a global variable isn't bad for a reentrant function.
|
I have astructwith one of its fields annotated withgcc type attribute.
```
struct str {
size_t size; /**< Size of string. */
char string[1] __attribute__ ((aligned(__BIGGEST_ALIGNMENT__))); /**< String. */
};
```
When I run doxygen on this code, struct memberstringis referenced not asData Field, but as aPublic Member Function. How do I make doxygen list this field as aData Field?
P.S. I have stringOPTIMIZE_OUTPUT_FOR_C = YESpresent in myDoxyfile.
|
In case it is correct that for the documentation the line
char string[1] __attribute__ ((aligned(__BIGGEST_ALIGNMENT__)));
can be
char string[1];
It would be sufficient to define in the doxygen configuration file:
PREDEFINED = __attribute__((x))=
|
I'm currently getting into binary exploitation, so far so good.
The only thing that I don't really understand is the difference between %4$d and %4d, for example. I was looking at this guide:
http://www.kroosec.com/2012/12/protostar-format2.html
and, on the last line, 'minimum field width' is mentioned while %60d is used. Is this related to my question? When should one use %$d and when %d?
|
The dollar sign inside a format string indicates a position of the variable used in printf. In this way, you may for example have only 1 parameter to the function, but use it 10 times in your format string, or with more parameters, in a different order. Depending on the programming language, you may or may not use mixed $ formatting.
|
```
result.author = (char *)malloc(sizeof(char)*strlen(temp->author));
strcpy(result.author, temp->author);
```
I'm doing an RPC thing, but that is not the question about.
Here i want to allocate and copy string "UNKNOWN" if temp is NULL like the below code.
```
result.author = (char *)malloc(sizeof(char)*strlen(temp->author || "UNKNOWN"));
strcpy(result.author, temp->author || "UNKNOWN");
```
How can i accomplish that?
|
```
result.author = malloc(strlen(temp->author ? temp.author : "UNKNOWN") + 1);
strcpy(result.author, temp->author ? temp.author : "UNKNOWN");
```
it is a shorthand of :
```
if(temp->author)
{
result.author = malloc(strlen(temp->author) + 1);
strcpy(result.author, temp->author);
}
else
{
result.author = malloc(strlen("UNKNOWN") + 1);
strcpy(result.author, "UNKNOWN");
}
```
|
I am trying to create a macro in c, that will take a variable name, and declare it. I could call it like this:
```
MY_MACRO(test);
```
Would produce:
```
int test;
```
In order to achieve this I went this way:
```
#define MY_MACRO(var) /
int ##var; /
```
But the compiler doesn't understand this. Does such syntax exist in C11?
|
I wouldn't recommend doing such a thing. Anyway, there are two problems. First of all, to skip a newline, you need\, not/.
Second, the##is wrong. What it does is concatenating thevarto theint. So withMY_MACRO(foo)you would getintfoo;, but you wantint foo;
The macro needs to be like this:
```
#define MY_MACRO(var) \
int var
```
|
I have structure like below.
```
struct result{
int a;
int b;
int c;
int d;
}
```
and union like below.
```
union convert{
int arr[4];
struct result res;
}
```
and I type pun as below.
```
int arr1[4] = {1,2,3,5};
union convert *pointer = (union convert *) arr1; // Here is my question, is it well defined?
printf("%d %d\n", pointer->res.a, pointer->res.b);
```
|
pointer->res.ais fine but the behaviour ofpointer->res.bis undefined.
There could be an arbitrary amount of padding between theaandbmembers.
Some compilers allow you to specify that there is no padding between members but of course then you are giving up portability.
|
Given that
```
void func(void **structs)
{
UI_Remote_s* a1 = (UI_Remote_s*)structs->Method; //expression
UI_Remote_s* a2 = ((UI_Remote_s*)structs)->Method; //correct
}
```
The first attempt is wrong. Why?
|
I would not use this type of casting as it makes code much harder to read. Instead use a temporary variable to store the pointer. It will make the code easier to read and understand. The compiler is very likely to optimize it oout in the generated code.
```
UI_Remote_s **ptr = (UI_Remote_s **)structs;
a2 = (*ptr) -> Method;
a2 = (*(ptr + 5)) -> Method;
a2 = ptr[2] -> Method;
.....
```
|
This is in Visual Studio 2015.
I have a native C library that I'm using from my .NET Visual C++ code. I'm aware that I have to change the "Common Language Runtime Support" option to "No Common Language Runtime Support" on the property page for each .c file, perthis question. However, even after I have turned that option off, I am still receiving error D8045 when I attempt to compile those files.
Is this a known issue in VS2015, or am I missing something?
|
It cleared up on its own eventually. I had restarted Visual Studio a few times and it kept happening, which is why I asked this question. I guess some cache somewhere wasn't being updated or got corrupt or something.
|
This is in Visual Studio 2015.
I have a native C library that I'm using from my .NET Visual C++ code. I'm aware that I have to change the "Common Language Runtime Support" option to "No Common Language Runtime Support" on the property page for each .c file, perthis question. However, even after I have turned that option off, I am still receiving error D8045 when I attempt to compile those files.
Is this a known issue in VS2015, or am I missing something?
|
It cleared up on its own eventually. I had restarted Visual Studio a few times and it kept happening, which is why I asked this question. I guess some cache somewhere wasn't being updated or got corrupt or something.
|
```
void rev(int n){
int rem;
printf("reverse of that number is:");
while(n>0)
{
rem=n%10;
n=n/10;
printf("%d",rem);
}
}
int main()
{
int n;
printf("enter a number of more than two digits");
scanf("%d",&n);
rev(n);
return 0;
}
```
This code without writing a piece of code for digits places i.e.,
```
reverse = reverse * 10 + remainder;
```
also returns the same.
please explain if there is any mistake in my perspective.
regards.
|
Because you actually didn't reverse number, you are just printing it. If you want to store reversed number and use it later, you have to to doreverse = reverse * 10 + remainder;
|
i don't understand why when i try to cast my double to int the values after the commas are rounded..
```
void print_float(double nb)
{
int negative;
int intpart;
double decpart = -10.754;
int v;
negative = (nb < 0.0f);
intpart = (int)nb;
decpart = nb - intpart;
v = (int)(decpart * 1000);
if (negative) {
v *= -1;
}
printf("%i.%i", intpart, v); // output: -10.753
}
```
I guess after thinking that the worries come from the cast, but I do not understand the problem..
|
Adoublecannot exactly encoded all numbers. It can exactly encoded about 264different values.-10.754is not one of them. Instead a nearby value is used just less than expected.
```
printf("%.24f", -10.754);
// -10.753999999999999559463504
```
Thedecpart * 1000part introduces some imprecision yet the product is still below 754.0 and then the(int)cast makes that 753.
|
I obtain a segmentation fault after the second cudaMalloc.
```
#include <cuda.h>
#include <cuda_runtime.h>
int main(){
int n=16;
float2* a;
cudaMalloc((void **) a, n*sizeof(float2));
float2* b;
cudaMalloc((void **) b, n*sizeof(float2));
return 0;
}
```
However, if I comment out any of the 2 cudaMallocs, the code runs fine.
Thanks!
|
You have to pass a pointer to the pointer like this:
```
float2* a;
cudaMalloc(&a, n*sizeof(float2));
float2* b;
cudaMalloc(&b, n*sizeof(float2));
```
otherwise, you just cast a dangling pointer to a "pointer to pointer" and the library dereferences a garbage address leading to a segfault.
|
I am implementing my own C/C++ app using the Qt framework.
I want to retrieve the last crash log of my app at the time it crashes and send it to my API.
Is there a Apple native or terminal way to retrieve the log or do I have to retrieve it the hard way?
Thank you in advance.
|
Yes, but only if you publish your software via App Store. Crash reports are then gathered by the OS and can be retrieved on the App-Store-developer site. The user has the last say in whether the reports are delivered to Apple/you however.
|
I am a student, a couple of years messing about with C but no solid period of practising the language. I am trying to perform a walking one and walking zero test on a byte and pretty stuck, any tips would be appreciated.
I have two questions.
1) How do I perform a walking Zero?
2) How do I perform a rotate right through carry (or left) in C?
I worked out a walking one bit of code, although this does not carry round and restart at bit 0
```
int8_t walkOne = 1;
walkOne <<= 1;
```
Walking Zero:
??
I know there must be a better way of doing this is anyone able to help?
Regards
|
C does not provide any rotate operation. However, you do not need one for this. To prepare the walking-one value for stepi, simply shift a one bit byi % 8bits:
```
uint8_t walkOne = 1u << i%8;
```
i%8is the remainder wheniis divided by eight.
For walking zeroes, complement the pattern:
```
uint8_t walkZero = ~(1u << i%8);
```
|
I want to check the content of a file from Linux Kernel v3.0.8 knowing onlystruct inode *. I only need to read the beginning of a file pointed by this inode, then close and return. I don't care about additional information like filename/mountpoint etc.. In fact, the file may not have the name (like deleted but still open). Is it possible?
|
I finally did it like this:
This is needed.
```
struct path root;
struct file *filerd;
```
Get the init task fs root.
```
task_lock(&init_task);
get_fs_root(init_task.fs, &root);
task_unlock(&init_task);
```
Change dentry to this file:
```
root.dentry = d_find_alias(inode);
```
Open file:
```
filerd = file_open_root(root.dentry->d_parent, root.mnt,
root.dentry->d_name.name, O_RDONLY);
```
It worked for every process I tested and for different mount points, which surprised me.
|
I have an fmp4 file (using h264 and aac frame codes). When playing with VLC, only video has no audio, but the audio can be parsed with PotPlayer.
The AAC format is ADTS.The screenshot of my fmp4 audio-related box is as follows
|
Mp4 should not have ADTS headers in the data. Just raw aac frames plus a configuration record in esds.
|
This code is supposed to find the smallest odd number in given array and store it inminbut when I try to printminit always prints0.
```
int smallestodd(int x[5]){
int j;
int k[5];
int p = 0;
int r = 0;
for(int h =0; h<5;h++){
j = x[h] % 2;
if(j == 1){
int temp =x[h];
k[p] =temp;
p++;
}
}
int min = k[0];
while(k[r] !=0){
if(k[r] < min ){
min = k[r];
r++;
}
}
return min;
}
```
|
Assuming there is an odd number in the array --let's say trying to find the minimum odd number in an array with just even numbers (or no numbers) is UB:)
```
index = 0;
while (arr[index] % 2 == 0) index++; // skip even numbers
min = arr[index++]; // first odd number
while (index < length) {
if (arr[index] % 2) {
if (arr[index] < min) min = arr[index];
}
index++;
}
```
|
I am using IAR embedded workbench software for ARM CORTEX M7 controller. I have already included stdio.h library and it have fopen function like this
but when i am declaring my file pointer like this
FILE *fpointer;
Its giving me these two errors.
Please share your experience how can i fix it?
|
File I/O is not present in the default library. To enable it you need to tell the compiler to use full libraries. This is done by opening the project options and choosing "Full" in the "Library Options" tab if you are using the IDE or by using the command line option--dlib_config fullif you are using the command line compiler.
In addition, unless you are ok with using semihosting for input and output, you need to implement the low level I/O interface for your target.
|
RC6wikiuses variable left rotation value that depends on logarithmic value. Iam interested in finding a way to implement constant time c code of RC6. Is there open-source or an idea of how to implement the variable left rotation in constant-time code.
|
This point is addressed in section 4.1 ofhttps://pdfs.semanticscholar.org/bf3e/23be81385817319524ee6bb1d62e9054d153.pdf. The short summary is:
Most processors take constant time for rotations including data dependent rotations (that was the case when rc6 was proposed anyway)Even if the run time to shift k bits is proportional to k cycles, then to do a circular left rotation you need to shift left k-bits followed by shift right 32-k bits, so that results in a constant time of 32 cycles.
I don't know fine details of modern architectures, but I suppose I would turn the question around and ask for an example where that logic is not true.
|
I'm compiling this code with C99 (with some different type definitions like uint32 instead of uint32_t) for an old arm architecture.
```
uint32 x2 = *((uint32 *) &data[t]);
uint32 x3;
memcpy(&x3, &data[t], 4);
printf("%d %d %d %d %d %d", x2, x3, data[t], data[t + 1], data[t + 2], data[t + 3]);
```
(data is uchar* and have length > t + 4)
but surprisingly the output is this:
```
-268435454 2 2 0 0 0
```
what is wrong with this casting?
|
Thex2line causes undefined behavior. Firstlydata[t]might not have 32-bit alignment, and secondly, it's probably a strict aliasing violation to read a 32-bit value from that location.
Just remove that line and use thex3version.
|
I'm rouhgly new to Atom Editor, and I wanted to program my media player, based onvlc/libvlc, with it, but I can't include any files fromlibvlc. I downloaded it through the terminal withsudo apt-get install libvlc-dev, but now I can't find the files to include it.
|
Since you installed usingapt-get, you should be able to locate the location of all the files from a particular package usingapt-file.
```
$ apt-file list libvlc-dev
```
Ifapt-fileisn't already on your system, install it.
```
$ sudo apt-get install apt-file
```
|
I want to check the content of a file from Linux Kernel v3.0.8 knowing onlystruct inode *. I only need to read the beginning of a file pointed by this inode, then close and return. I don't care about additional information like filename/mountpoint etc.. In fact, the file may not have the name (like deleted but still open). Is it possible?
|
I finally did it like this:
This is needed.
```
struct path root;
struct file *filerd;
```
Get the init task fs root.
```
task_lock(&init_task);
get_fs_root(init_task.fs, &root);
task_unlock(&init_task);
```
Change dentry to this file:
```
root.dentry = d_find_alias(inode);
```
Open file:
```
filerd = file_open_root(root.dentry->d_parent, root.mnt,
root.dentry->d_name.name, O_RDONLY);
```
It worked for every process I tested and for different mount points, which surprised me.
|
I have an fmp4 file (using h264 and aac frame codes). When playing with VLC, only video has no audio, but the audio can be parsed with PotPlayer.
The AAC format is ADTS.The screenshot of my fmp4 audio-related box is as follows
|
Mp4 should not have ADTS headers in the data. Just raw aac frames plus a configuration record in esds.
|
This code is supposed to find the smallest odd number in given array and store it inminbut when I try to printminit always prints0.
```
int smallestodd(int x[5]){
int j;
int k[5];
int p = 0;
int r = 0;
for(int h =0; h<5;h++){
j = x[h] % 2;
if(j == 1){
int temp =x[h];
k[p] =temp;
p++;
}
}
int min = k[0];
while(k[r] !=0){
if(k[r] < min ){
min = k[r];
r++;
}
}
return min;
}
```
|
Assuming there is an odd number in the array --let's say trying to find the minimum odd number in an array with just even numbers (or no numbers) is UB:)
```
index = 0;
while (arr[index] % 2 == 0) index++; // skip even numbers
min = arr[index++]; // first odd number
while (index < length) {
if (arr[index] % 2) {
if (arr[index] < min) min = arr[index];
}
index++;
}
```
|
I am using IAR embedded workbench software for ARM CORTEX M7 controller. I have already included stdio.h library and it have fopen function like this
but when i am declaring my file pointer like this
FILE *fpointer;
Its giving me these two errors.
Please share your experience how can i fix it?
|
File I/O is not present in the default library. To enable it you need to tell the compiler to use full libraries. This is done by opening the project options and choosing "Full" in the "Library Options" tab if you are using the IDE or by using the command line option--dlib_config fullif you are using the command line compiler.
In addition, unless you are ok with using semihosting for input and output, you need to implement the low level I/O interface for your target.
|
RC6wikiuses variable left rotation value that depends on logarithmic value. Iam interested in finding a way to implement constant time c code of RC6. Is there open-source or an idea of how to implement the variable left rotation in constant-time code.
|
This point is addressed in section 4.1 ofhttps://pdfs.semanticscholar.org/bf3e/23be81385817319524ee6bb1d62e9054d153.pdf. The short summary is:
Most processors take constant time for rotations including data dependent rotations (that was the case when rc6 was proposed anyway)Even if the run time to shift k bits is proportional to k cycles, then to do a circular left rotation you need to shift left k-bits followed by shift right 32-k bits, so that results in a constant time of 32 cycles.
I don't know fine details of modern architectures, but I suppose I would turn the question around and ask for an example where that logic is not true.
|
I'm compiling this code with C99 (with some different type definitions like uint32 instead of uint32_t) for an old arm architecture.
```
uint32 x2 = *((uint32 *) &data[t]);
uint32 x3;
memcpy(&x3, &data[t], 4);
printf("%d %d %d %d %d %d", x2, x3, data[t], data[t + 1], data[t + 2], data[t + 3]);
```
(data is uchar* and have length > t + 4)
but surprisingly the output is this:
```
-268435454 2 2 0 0 0
```
what is wrong with this casting?
|
Thex2line causes undefined behavior. Firstlydata[t]might not have 32-bit alignment, and secondly, it's probably a strict aliasing violation to read a 32-bit value from that location.
Just remove that line and use thex3version.
|
I'm rouhgly new to Atom Editor, and I wanted to program my media player, based onvlc/libvlc, with it, but I can't include any files fromlibvlc. I downloaded it through the terminal withsudo apt-get install libvlc-dev, but now I can't find the files to include it.
|
Since you installed usingapt-get, you should be able to locate the location of all the files from a particular package usingapt-file.
```
$ apt-file list libvlc-dev
```
Ifapt-fileisn't already on your system, install it.
```
$ sudo apt-get install apt-file
```
|
I tried to compute the inner product using function but the returned value is not correct.
```
/* Inner product x[n]*y[n] */
#include <stdio.h>
#define n 5
void main()
{
int i,sum;
int x[n]={1,2,-1,3,5};
int y[n]={0,6,-2,4,1};
sum=inner_prod(x[n],y[n]);
printf("\nThe inner product = %d",sum);
}
int inner_prod( int a[n], int b[n] )
{
int i, s=0;
for(i=0;i<n;i++)
s=s+b[i]*a[i];
return (s);
}
```
|
The dot product of the two vectors x,y in your case should result in 31 and would do so with your inner_prod function, but you calculated the dot product for x * x which in your case results in 40..
In short, isn't the problem that you just made a typo?
```
sum=inner_prod(x[n],x[n]);
```
I believe you wanted for this to have been the following?
```
sum=inner_prod(x,y);
```
|
```
char *a = malloc(10);
memset(a, 10, 0);
a[0]= 'a';
a[1]= 6;
a[2]= 'b';
printf("%s\n", a); // prints ab
a[0]= 'a';
a[1]= 27;
a[2]= 'b';
printf("%s\n", a); // print a
return 1;
```
Is it safe to put control char in string? like in strcpy, etc..
|
C strings are NUL-terminated sequences ofchars (bytes). Nothing more. Therefore, the control characters have no special meaning to the language or tostrcpy.
Functions that care about the contents of strings will define which characters have special meanings.
|
Recently bought a new USB oscilloscope and tried to measure the frequency of avr timer0. There is 12 MHz crystal oscillator connected to atmega and timer0 set up to fast PWM mode without prescaler. Here is the code:
```
#include <avr/io.h>
int main(void)
{
DDRB = 0x08;
TCCR0 |= (1<<WGM00)|(1<<WGM01)|(1<<COM01)|(1<<CS00);
OCR0 = 128;
while(1){
}
}
```
But on oscilloscope frequency equals 46.90 kHz.
Fuse bits are on the next image:
But if I blink a LED with a delay of 1 ms, I got frequency around 2 MHz.
So, please explain to me, what's going on, and why timer works wrong (or where I'm wrong).
|
The frequency seems correct to me. If your clock is12MHzand you have an 8 bit PWM your PWM frequency is actually12MHz/256 = 46.875kHz.
|
I was going through an online lecture and I saw this function to sum an array
```
int arraySum(int array[], const int n)
{
int sum = 0, *ptr;
int *const arrayEnd = array + n;
...
}
```
I've not seen an array added to an integer before. If n is the size of the array, does array + n mean that arrayEnd is assigned a value of the last element in array[] or does it mean something else like the address of that element?
|
What you're seeing is pointer arithmetic.
arrayis a pointer to the start of your array. Assuming the array hasnelements, thenarray + n(or equivalently&array[n]) points to one element past the end of the array.
It is legal to have a pointer to one element past the end of an array, however you can't dereference that pointer.
|
Is there a way to start a child process withoutfork(), usingexecvp()exclusively?
|
The pedantic answer to your question is no. Theonlysystem call that creates a new process isfork. The system call underlyingexecvp(calledexecve) loads a newprograminto an existing process, which is a different thing.
Some species of Unix have additional system calls besidesfork(e.g.vfork,rfork,clone) that create a new process, but they are only small variations onforkitself, and none of them are part of the POSIX standard that specifies the functionality you can count on onanythingthat calls itself a Unix.
The slightly more helpful answer is that you might be looking forposix_spawn, which is a library routine wrappingforkandexecinto a single operation, but I find itmoretroublesome to use that correctly than to write my ownfork+execsubroutine. YMMV.
|
I am trying to create a socket as follow but it is failing with error address family not supported. Can any one please help me out as i am beginner to socket.
```
socket(AF_ATMPVC, SOCK_STREAM, 0);
```
If any other information is required please let me know in comments.
|
Apparently, I managed to find an answer for my question. This problem can be fixed by passing--network=hostoption while creating the docker container.If you use the host network driver for a container, that container’s network stack is not isolated from the Docker host.
|
I was going through an online lecture and I saw this function to sum an array
```
int arraySum(int array[], const int n)
{
int sum = 0, *ptr;
int *const arrayEnd = array + n;
...
}
```
I've not seen an array added to an integer before. If n is the size of the array, does array + n mean that arrayEnd is assigned a value of the last element in array[] or does it mean something else like the address of that element?
|
What you're seeing is pointer arithmetic.
arrayis a pointer to the start of your array. Assuming the array hasnelements, thenarray + n(or equivalently&array[n]) points to one element past the end of the array.
It is legal to have a pointer to one element past the end of an array, however you can't dereference that pointer.
|
Is there a way to start a child process withoutfork(), usingexecvp()exclusively?
|
The pedantic answer to your question is no. Theonlysystem call that creates a new process isfork. The system call underlyingexecvp(calledexecve) loads a newprograminto an existing process, which is a different thing.
Some species of Unix have additional system calls besidesfork(e.g.vfork,rfork,clone) that create a new process, but they are only small variations onforkitself, and none of them are part of the POSIX standard that specifies the functionality you can count on onanythingthat calls itself a Unix.
The slightly more helpful answer is that you might be looking forposix_spawn, which is a library routine wrappingforkandexecinto a single operation, but I find itmoretroublesome to use that correctly than to write my ownfork+execsubroutine. YMMV.
|
I am trying to create a socket as follow but it is failing with error address family not supported. Can any one please help me out as i am beginner to socket.
```
socket(AF_ATMPVC, SOCK_STREAM, 0);
```
If any other information is required please let me know in comments.
|
Apparently, I managed to find an answer for my question. This problem can be fixed by passing--network=hostoption while creating the docker container.If you use the host network driver for a container, that container’s network stack is not isolated from the Docker host.
|
This question already has answers here:typedef struct vs struct definitions [duplicate](12 answers)Closed4 years ago.
Let's say I have this definition:
```
typedef struct tnode *Tnodep;
typedef struct tnode
{
int contents; /* contents of the node */
Tnodep left, right; /* left and right children */
}Tnode;
```
What's does the last Tnode means? and what's the difference between this definition and this definition?
```
typedef struct tnode *Tnodep;
typedef struct tnode
{
int contents; /* contents of the node */
Tnodep left, right; /* left and right children */
};
```
|
The first definition defines a struct tnode, and two type names Tnodep and Tnode. The second one doesn't define the type name Tnode.
With the first definition, you can then define either of the following two:
```
Tnode x;
tnode y;
```
With the second definition, you can't. You can only write
```
struct tnode x;
```
|
I have two libraries and unfortunately they define two identical preprocessor definitions (which I need to use):
lib1.h
```
#define MYINT 1
```
lib2.h
```
#define MYINT 2
```
In my program I need to use both of them:
```
#include <Lib1.h>
#include <lib2.h>
...
int myint = MYINT;
```
And here I have error that MYINT can't be resolved.
How can I solve that when I cannot modify the lib files?
|
You might#undef MYINTbefore to include the header as workaround.
```
#undef MYINT
#include <Lib1.h>
const int myint_lib1 = MYINT; // 1
#undef MYINT
#include <lib2.h>
const int myint_lib2 = MYINT; // 2
```
|
I am writing a C program that does many comparisons and I was wondering if this actually saves memory.
Any help appreciated
|
No, it does not. Using a tricky syntax to do something that there's a well-known syntax for is never the right answer. You should use x==a.
|
I have a program that should be CPU bound, but it is using well less than 100% CPU, and is not consuming input as fast as it can. It means my process is blocking or sleeping somewhere.
How to find what calls are blocking my process for the most time? Is there a tool or debugging procedure that measures the time how much time the process is asleep on each blocking system call?
|
straceis an option:
```
$ strace -wc sleep 1
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
99.96 1.000146 1000146 1 nanosleep
0.01 0.000131 131 1 execve
0.01 0.000082 10 8 mmap
[...]
```
|
I get the frame at0xffffd3d0and saveedeip = 0xf7e04e7ein stack level 0 while doing gdb debug.
```
(gdb) info frame
Stack level 0, frame at 0xffffd3d0:
eip = 0x8048452 in main (test.c:13); saved eip = 0xf7e04e7e
source language c.
Arglist at 0xffffd3b8, args:
Locals at 0xffffd3b8, Previous frame's sp is 0xffffd3d0
Saved registers:
ebp at 0xffffd3b8, eip at 0xffffd3cc
(gdb)
```
Here is my question about 3GB address space of userspace. Why it is showing frame pointer in out of 3GB address space ?
Normally, the address space of the user space is 0 to0xc000000in a 3: 1 virtual address distribution.
|
3GB limit does not apply to 64-bit processes
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.