Menu
  • HOME
  • TAGS

Obtaining wrong result when using PyFloat_FromDouble in a C function called from Python

python,c,arrays

The default precision for printf output is I think 6 decimal places. Could it be just that your printf function is rounding the answer to 3.600000 and python is being more accurate in it's printing?...

user defined printf failed to print float value

c

if( *p=='%' ) should read if( *p != '%' ). You want to print out characters that are not %, and enter the switch when you do encounter a %. What's actually happening is that you enter your switch statement for all the non-% characters and there's no case for...

binary tree code does not work properly

c,pointers

It looks like you never assign any value to root. Remember, C passes arguments by value, so when you call enter(root, word); from scan(), enter() can't change the value of root. It changes its local copy of it, though, but that is not enough. The same problem occurs when you...

Unexpected output printf statement [duplicate]

c,macros,printf,ternary-operator

k==MAX(i++,++j); is translated to: k==(i++) > (++j) ? (i++) : (++j); /* 2 1 3 : Precedance */ In your case i = 10 and j = 5, so the comparision would be 10 v/s 6 which would be true or 1 with side effect i becomes 11 and j...

What all local variables goto Data/BSS segment?

c++,c,nm

"local" in this context means file scope. That is: static int local_data = 1; /* initialised local data */ static int local_bss; /* uninitialised local bss */ int global_data = 1; /* initialised global data */ int global_bss; /* uninitialised global bss */ void main (void) { // Some code...

How to make new line when using echo to write a file in C

c,linux,file,echo,system

There is one new line, which is to be expected. The echo command prints all its arguments on a single line separated by spaces, which is the output you see. You need to execute the result of: echo "$(ls %s)" to preserve the newlines in the ls output. See Capturing...

Efficient comparison of small integer vectors

c,integer,compare,bit-manipulation,string-comparison

It's possible to do this using bit-manipulation. Space your values out so that each takes up 5 bits, with 4 bits for the value and an empty 0 in the most significant position as a kind of spacing bit. Placing a spacing bit between each value stops borrows/carries from propagating...

fread(), solaris to unix portability and use of uninitialised values

c,linux,memory,stack,portability

Q 1. why is ch empty even after fread() assignment? (Most probably) because fread() failed. See the detailed answer below. Q 2.Is this a portability issue between Solaris and Linux? No, there is a possible issue with your code itself, which is correctly reported by valgrind. I cannot quite...

Matlab Crahes upon fopen in Mex File

c,matlab,fopen,mex

Use w+ or r+ when using fopen, depending on what you want to do with the file and whethe you want to create it or simply open it. From (http://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm) "r" Opens a file for reading. The file must exist. "w" Creates an empty file for writing. If a file...

Returning a pointer which is a locally declared wchar_t

c,static,scope,return

It's OK to return a local variable, it's not OK to return a pointer to a local variable. int foo(void) { int var = 42; return var; //OK } int *bar(void) { int var = 42; return &var; //ERROR } In the case of returning a pointer, all it matters...

Array breaking in Pebble C

c,arrays,pebble-watch,cloudpebble

The problem is this line static char *die_label = "D"; That points die_label to a region of memory that a) should not be written to, and b) only has space for two characters, the D and the \0 terminator. So the strcat is writing into memory that it shouldn't be....

How to call Fortran routine with unit number argument from C

c,io,fortran,shared-libraries,abi

This is completely compiler dependent, there is no portable correspondence. See the manual of your compiler if they support some sort of interoperability as an extension.

OpenGL glTexImage2D memory issue

c,opengl

Which man page are you quoting? There are multiple man pages available, not all mapping to the same OpenGL version. Anyways, the idea behind the + 2 (border) is to have 2 multiplied by the value of border, which is in your case 0. So your code is just fine....

Is there an equivalent of Haskell's `let`/`in` in C Preprocessor Macros?

c,c-preprocessor

Could not be simply... #define INDEX_OF(prime,mod) (prime / 3 - (mod == 0 || mod == 3 || mod == 4)); ...

execl() works on one of my code, but doesn't work on another

c,execl

My C is a bit rusty but your code made many rookie mistakes. execl will replace the current process if it succeeds. So the last line ("i have no idea why") won't print if the child can launch successfully. Which means... execl failed and you didn't check for it! Hint:...

Can I use STDIN for IPC?

c,gcc,ipc,stdin

You can use pipe for IPC. Now if you want to use STDIN_FILENO and STDOUT_FILENO it would look like this: #include <unistd.h> #include <stdio.h> int main(void) { char val = '!'; int filedes[2]; pipe(filedes); int proc = fork(); if (proc < 0) return -1; if (proc == 0) { close(1);...

Segmentation Fault if I don't say int i=0

c,arrays,segmentation-fault,initialization,int

In your code, int i is an automatic local variable. If not initialized explicitly, the value held by that variable in indeterministic. So, without explicit initialization, using (reading the value of ) i in any form, like array[i] invokes undefined behaviour, the side-effect being a segmentation fault. Isn't it automatically...

is return main(); a valid syntax?

c,function,return,language-lawyer,return-type

I didn't know that the return statement accepts any parameter that can be evaluated to the expected return data type, Well, a return statement can have an expression. Quoting C11 standard, chapter 6.8.6.4, The return statement. If a return statement with an expression is executed, the value of the...

How to pass pointer to struct to a function?

c,function,pointers,struct

Inside your doStuff() function, myCoords is already a pointer. You can simply pass that pointer itself to calculateCoords() and calculateMotorSpeeds() function. Also, with a function prototype like void calculateCoords(struct coords* myCoords) calling calculateCoords(&myCoords); from doStuff() is wrong, as it is passing struct coords**. Solution: Keep your function signature for calculateCoords()...

CGO converting Xlib XEvent struct to byte array?

c,go,xlib,cgo

As mentioned in the cgo documentation: As Go doesn't have support for C's union type in the general case, C's union types are represented as a Go byte array with the same length. Another SO question: Golang CGo: converting union field to Go type or a go-nuts mailing list post...

C programming - Confusion regarding curly braces

c,scope

The only difference between the two is the scope of the else. Without the braces, it spans until the end of the full statement, which is the next ;, i.e the next line: else putchar(ch); /* end of else */ lastch = ch; /* outside of if-else */ With the...

LOAD DATA in C The used command is not allowed

mysql,c,load-data-infile

Now it's working with change to explicitly set MYSQL_OPT_LOCAL_INFILE option. Useful links Security Issues with LOAD DATA LOCAL mysql_options() MYSQL_OPT_LOCAL_INFILE option info MYSQL_OPT_LOCAL_INFILE (argument type: optional pointer to unsigned int) If no pointer is given or if pointer points to an unsigned int that has a nonzero value, the LOAD...

C++ / C #define macro calculation

c++,c,macros

Are DETUNE1 and DETUNE2 calculated every time it is called? Very unlikely. Because you are calling sqrt with constants, most compilers would optimize the call to the sqrt functions and replace it with a constant value. GCC does that at -O1. So does clang. (See live). In the general...

C binary tree sort - extending it

c,binary-tree,binary-search-tree

a sample to modify like as void inorder ( struct btreenode *, int ** ) ; int* sort(int *array, int arr_size) { struct btreenode *bt = NULL; int i, *p = array; for ( i = 0 ; i < arr_size ; i++ ) insert ( &bt, array[i] ) ;...

Set precision dynamically using sprintf

c,printf,format-string

Yes, you can do that. You need to use an asterisk * as the field width and .* as the precision. Then, you need to supply the arguments carrying the values. Something like sprintf(myNumber,"%*.*lf",A,B,a); Note: A and B need to be type int. From the C11 standard, chapter §7.21.6.1, fprintf()...

Infinite loop with fread

c,arrays,loops,malloc,fread

If you're "trying to allocate an array 64 bytes in size", you may consider uint8_t Buffer[64]; instead of uint8_t *Buffer[64]; (the latter is an array of 64 pointers to byte) After doing this, you will have no need in malloc as your structure with a 64 bytes array inside is...

CallXXXMethod undefined using JNI in C

java,c,jni

There are few fixes required in the code: CallIntMethod should be (*env)->CallIntMethod class Test should be public Invocation should be jint age = (*env)->CallIntMethod(env, mod_obj, mid, NULL); Note that you need class name to call a static function but an object to call a method. (cls2 -> person) mid =...

Is i=i+1 an undefined behaviour?

c,increment,undefined-behavior

There is no undefined behavior in this code. i=i+1; is well-defined behavior, not to be confused with i=i++; which gives undefined behavior. The only thing that could cause different outputs here would be floating point inaccuracy. Try value += 4 * (int)nearbyint(pow(10,i)); and see if it makes any difference....

Code knight's tour using backtracking is not showing any output

c++,c,graph

Replacing the following code: if(movei == (N*N)+1){ return true; } ...with a hardcoded value... if(movei == 62){ return true; } ...gave me a good result after 0.1 seconds. (A field with only three "zeroes" remaining.) So your overall algorithm works. Hint for better looks of the output: #include <iomanip> cout...

Freeing array of dynamic strings / lines in C

c,string,sorting,malloc,free

There are multiple problems in your code: function getline: the string in the line buffer is not properly '\0' terminated at the end of the do / while loop. It does not free the line buffer upon end of file, hence memory leak. It does not return a partial line...

How do I let the user name the output.txt file in my C program?

c,file

You can read the input from user and append .txt char fileName[30]; // ... scanf("%25s", fileName); // max 25 characters because .txt have 4 (25+4 = 29) strcat(fileName, ".txt"); // append .txt extension // ... FILE *f = fopen(fileName, "a"); ...

Is there Predefined-Macros define about byte order in armcc

c,armcc,predefined-macro

Well according to this page: http://www.keil.com/support/man/docs/armccref/armccref_BABJFEFG.htm You have __BIG_ENDIAN which is defined when compiling for a big endian target....

Access violation on try to fill dynamic array (large number of items)

c,arrays,pointers,malloc,dynamic-memory-allocation

"Access violation writing location 0x00000000" is explained by the manual http://man7.org/linux/man-pages/man3/malloc.3.html#RETURN_VALUE On error, these functions return NULL. Or if you prefer http://www.cplusplus.com/reference/cstdlib/malloc/. Return Value On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the...

Is it safe to read and write on an array of 32 bit data byte by byte?

c,memory,memory-alignment

Yes, this is correct. The only danger would be generating a bit pattern that does not correspond to any int, but on modern systems there are no such patterns. Also, if the data type was uint32_t specifically, those are prohibited from having any such patterns anyway. Note that the inverse...

XV6 crashes when trying to implement triple indirection in xv6 operating system

c,xv6

1.The number of nblocks which is defined in mkfs.c is insufficient. int nblocks = 20985; int nlog = LOGSIZE; int ninodes = 200; int size = 21029; You have defined: #define MAXFILE (NDIRECT + NINDIRECT + NINDIRECT*NINDIRECT + 4*NINDIRECT*NINDIRECT which equals: 10+128+128^2+4*128^2 = 82058. Just pick a number of nblocks...

Galois LFSR - how to specify the output bit number

c,prng,shift-register

If you need bit k (k = 0 ..15), you can do the following: return (lfsr >> k) & 1; This shifts the register kbit positions to the right and masks the least significant bit....

Is post-increment operator guaranteed to run instantly?

c,c89,post-increment,ansi-c

This code is broken for two reasons: Accessing a variable twice between sequence points, for other purposes than to determine which value to store, is undefined behavior. There are no sequence points between the evaluation of function parameters. Meaning anything could happen, your program might crash & burn (or more...

libX11: XPutImage first call

c,x11

The trick is to wait that the windows is mapped. You can do this by Expose event. int main(int argc, char **argv) { int win_b_color; int win_w_color; XEvent xev; Window window; GC gc; Display *display = XOpenDisplay(NULL); Visual *visual; XImage *ximage; win_b_color = BlackPixel(display, DefaultScreen(display)); win_w_color = BlackPixel(display, DefaultScreen(display)); window...

free causing different results from malloc

c,string,malloc,free

Every time you are creating your string, you are not appending a null terminator, which causes the error. So change this: for(j=0; j<rem_len; j++) { if(j != i) { remaining_for_next[index_4_next] = remaining[j]; index_4_next++; } } to this: for(j=0; j<rem_len; j++) { if(j != i) { remaining_for_next[index_4_next] = remaining[j]; index_4_next++; }...

How to control C Macro Precedence

c,macros

You can redirect the JOIN operation to another macro, which then does the actual pasting, in order to enforce expansion of its arguments: #define VAL1CHK 20 #define NUM 1 #define JOIN1(A, B, C) A##B##C #define JOIN(A, B, C) JOIN1(A, B, C) int x = JOIN(VAL,NUM,CHK); This technique is often used...

How convert unsigned int to unsigned char array

c++,c

#include <stdio.h> int main() { unsigned int i = 0x557e89f3; unsigned char c[4]; c[0] = i & 0xFF; c[1] = (i>>8) & 0xFF; c[2] = (i>>16) & 0xFF; c[3] = (i>>24) & 0xFF; printf("c[0] = %x \n", c[0]); printf("c[1] = %x \n", c[1]); printf("c[2] = %x \n", c[2]); printf("c[3] =...

What does `strcpy(x+1, SEQX)` do?

c,strcpy

The pointer + offset notation is used as a convenient means to reference memory locations. In your case, the pointer is provided by malloc() after allocating sufficient heap memory, and represents an array of M + 2 elements of type char, thus the notation as used in your code represents...

getchar() not working in c

c,while-loop,char,scanf,getchar

That's because scanf() left the trailing newline in input. I suggest replacing this: ch = getchar(); With: scanf(" %c", &ch); Note the leading space in the format string. It is needed to force scanf() to ignore every whitespace character until a non-whitespace is read. This is generally more robust than...

Why is my C code printing out an extra line of rows?

c,loops,for-loop,macros,printf

There is no issue with the #define, there is one issue with the conditional statement in the for loop. I believe, you'er overlooking the <= operator. You need to have only < operator. Change for(i=0;i<=rows;++i) to for(i=0;i<rows;++i) That said, the recommended signature of main() is int main(void)....

strcmp performance in C

c,string,algorithm,data-structures

Yes, this is in O(n) in the average and worst case, where n is the length of the shorter of both given strings. You could also express that as O(min(m,n)) with m and n being the lengths of both strings, respectively. But no, O(n) doesn't mean that it needs exactly...

How could I simulate a lack of file descriptor?

c,linux,file-descriptor

You can limit the number of file descriptors a process can open under Linux using ulimit. Executing ulimit -n 3 before running your C program should make it an error to open any more files, since stdin, stdout, and stderr take up the first 3 descriptors. An example: $ ulimit...

What is the difference between glUseProgram() and glUseShaderProgram()?

c++,c,opengl,shader

glUseShaderProgramEXT() is part of the EXT_separate_shader_objects extension. This extension was changed significantly in the version that gained ARB status as ARB_separate_shader_objects. The idea is still the same, but the API looks quite different. The extension spec comments on that: This extension builds on the proof-of-concept provided by EXT_separate_shader_objects which demonstrated...

Makefile: wildcard and patsubst does not change file source names

c,makefile

It seems you've mixed up some things here. They are basically two type of rules you need to use here, and they both share the same syntax: targets : prerequisites recipe When you write this: $(APP): $(OBJS) $(CC) $(CFLAGS) $< -o [email protected] $(LDFLAGS) You're saying to make that you want...

search string in textfile [on hold]

c++,c,string,text

If using C/C++ is not mandatory, then grep is probably your friend : grep "size [0-9]*" -o yourfile.txt > all_sizes.txt And if you only need the 50 first results, head it is : head -n 50 all_sizes > result.txt (Now, this assumes you're using some kind of Unix, or OS...

MessageBox won't work when handling WM_DESTROY event from DialogBox

c,user-interface,winapi

When you use DialogBox rather than DialogBoxParam, the dialog runs its own message loop that handles WM_DESTROY internally. When you post the WM_QUIT message from your dialog procedure you are generating an additional message* that the dialog box won't use, so it remains in your thread's message queue once the...

Recursive signal call using kill function

c,signals

Historically, lots of details about how signals work have changed. For instance, in the earliest variant, the processing of the signal reverted to default when the handler was called, and the handler had to re-establish itself. In this situation, sending the signal from the handler would kill the process. Currently,...

How to read string until two consecutive spaces?

c,format,sscanf,c-strings

The scanf family of functions are good for simple parsing, but not for more complicated things like you seem to do. You could probably solve it by using e.g. strstr to find the comment starter "//", terminate the string there, and then remove trailing space....

Program Runs Fine for Hours and Eventually Seg Faults with Memory Address 0x10 [closed]

c++,c,memory,arm

I predict that your struct is being dynamically allocated via new or malloc and someone is either eating the std::bad_alloc exception without handling it or ignoring a NULL return. An address of 0x10 is almost certainly NULL plus the struct member offset. That would also explain the zeroed fields because...

Explanation of why allocating a large array results in segmentation fault in C [duplicate]

c,arrays,memory-management

It depends where you allocated the array. If it's inside a function, then the variable is allocated on the stack, and by default, (I assume you're running linux) the stack size is 8Mb. You can find it out using ulimit -s and also modify this value, for instance ulimit -s...

Casting double to integer when is it undefined behaviour

c++,c

From [conv.fpint]: A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. So, for example, converting 66666.66 to...

How does ((a++,b)) work? [duplicate]

c,function,recursion,comma

In your first code, Case 1: return reverse(i++); will cause stack overflow as the value of unchanged i will be used as the function argument (as the effect of post increment will be sequenced after the function call), and then i will be increased. So, it is basically calling the...

VS2012 Identifer not found when part of static lib

c,visual-studio-2012,linker,static-libraries

C++ uses something called name mangling when it creates symbol names. It's needed because the symbol names must contain the complete function signature. When you use extern "C" the names will not be mangled, and can be used from other programming languages, like C. You clearly make the shunt library...

Get RSA keys in a “simple” form

c++,c,encryption,openssl,rsa

This is the simple form - including the header and footer and extra newlines. Most certificate programs can handle this form just fine.

How exactly do pointers in Fortran differ from C/C++ pointers?

c++,c,pointers,fortran

As Mark says, pointers to functions and subroutines certainly do exist in Fortran. The differences are: In C, pointers are just an address whereas in Fortran, a pointer can have additional information such as array bounds and strides, which is why an explicit interface is required when declaring a pointer...

Typecasting int to char, then search array

c,arrays,string,casting,int

Use cast_number/*char*/ = (char) help_variable_remove_pv + '0'/*int*/; instead of cast_number/*char*/ = (char) help_variable_remove_pv/*int*/; A character and an integer somewhat are different. This means that '0'(character 0) and integer 0 aren't equal. You'll have to add 48 (ASCII value of '0') to 0 to get the integer value of '0'. See...

Passing int using char pointer in C

c,exec,ipc

Programs simply do not take integers as arguments, they take strings. Those strings can be decimal representations of integers, but they are still strings. So you are asking how to do something that simply doesn't make any sense. Twenty is an integer. It's the number of things you have if...

Program to reverse a string in C without declaring a char[]

c,string,pointers,char

Important: scanf(" %s", name); has no bounds checking on the input. If someone enters more than 255 characters into your program, it may give undefined behaviour. Now, you have the char array you have the count (number of char in the array), why do you need to bother doing stuffs...

C language, vector of struct, miss something?

c,vector,struct

What is happening is that tPeca pecaJogo[tam]; is a local variable, and as such the whole array is allocated in the stack frame of the function, which means that it will be deallocated along with the stack frame where the function it self is loaded. The reason it's working is...

RSA decrypt message [closed]

c++,c,openssl,cryptography,rsa

I found the problem. After adding errors checks, I've got error "3132:error:0906D06C:lib(9):func(109):reason(108):.\crypto\pem\pem_lib.c:703:Expe cting: ANY PRIVATE KEY". After googling and reading the manuals, I understood that my private key was initialized wrong. I needed to add \n after each line in private key (after each 64th symbol). So the key in...

Unexpected result when calculating a percentage - even when factoring in integer division rules

c,percentage,integer-overflow,integer-division

Diagnosis The value you expect is, presumably, 91. The problem appears to be that your compiler is using 16-bit int values. You should identify the platform on which you're working and include information about unusual situations such as 16-bit int types. It is reasonable for us to assume 32-bit or...

Text justification C language

c,text,alignment

From printf's manual: The field width An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead...

Loop through database table and compare user input

mysql,c

If you are only looking for fields that match the input, you'll want to search the database using the input string. In other words, write your query string so that it only gives you results that match the user input. This will be much faster than searching through every returned...

Why we should not use String for Storing password in Java but can use String for Storing password in C language? [duplicate]

java,c

In Java,Strings are immutable,so once you use String to store a password,there is no way that content can be changed because any change will produce new String. And the String which contains the password,will be available in memory until it got garbage collected. So it will be remain in memory...

When BSD socket reports that RST was received, if not everything was read yet

c,sockets,tcp

Will the first call to send() return an ECONNRESET? Not unless it blocks for long enough for the peer to detect the incoming packet for the broken connection and return an RST. Most of the time, send will just buffer the data and return. will the next call to...

Reverse ^ operator for decryption

c,algorithm,security,math,encryption

This is not a power operator. It is the XOR operator. The thing that you notice for the XOR operator is that x ^ k ^ k == x. That means that your encryption function is already the decryption function when called with the same key and the ciphertext instead...

Does strlen() always correctly report the number of char's in a pointer initialized string?

c,strlen

What strlen does is basically count all bytes until it hits a zero-byte, the so-called null-terminator, character '\0'. So as long as the string contains a terminator within the bounds of the memory allocated for the string, strlen will correctly return the number of char in the string. Note that...

C character array and its length

c,c-strings

You are hitting what is considered to be undefined behavior. It's working now, but due to chance, not correctness. In your case, it's because the memory in your program is probably all zeroed out at the beginning. So even though your string is not terminated properly, it just so happens...

assembly function with C segfault

c,assembly,x86,sse,fpu

You have forgotten to cleanup the stack. In the prologue you have: pushl %eax pushl %ecx pushl %edx pushl %ebp movl %esp, %ebp You obviously need to undo that before you ret, such as: movl %ebp, %esp popl %ebp popl %edx popl %ecx popl %eax ret PS: I have already...

On entry to NIT parameter number 9 had an illegal value

c,mpi,intel-mkl,mpich,scalapack

This answer is courtesy of Ying from Intel, all the credits go to him! The int in C are supposed to be 32bit, you may try lp64 mode. mpicc -o test_lp64 ex1.c -I/opt/intel/mkl/include /opt/intel/mkl/lib/intel64/libmkl_scalapack_lp64.a -L/opt/intel/mkl/lib/intel64 -Wl,--start-group /opt/intel/mkl/lib/intel64/libmkl_intel_lp64.a /opt/intel/mkl/lib/intel64/libmkl_core.a /opt/intel/mkl/lib/intel64/libmkl_sequential.a -Wl,--end-group /opt/intel/mkl/lib/intel64/libmkl_blacs_intelmpi_lp64.a -lpthread -lm -ldl [[email protected] scalapack]$ mpirun -n 4...

Use emscripten from Clang compiled executable

c++,c,clang,emscripten

Porting to Emscripten is the same as porting to any other platform: you have to use that's platform's own platform-specific headers. Some will have nice equivalents, and some won't. In most cases you'll need to find these chains of platform-specific #if defined(...) and add an #elif defined(__EMSCRIPTEN__), and do the...

Segmentation fault with generating an RSA and saving in ASN.1/DER?

c,openssl,cryptography,rsa

pub_l = malloc(sizeof(pub_l)); is simply not needed. Nor is priv_l = malloc(sizeof(priv_l));. Remove them both from your function. You should be populating your out-parameters; instead you're throwing out the caller's provided addresses to populate and (a) populating your own, then (b) leaking the memory you just allocated. The result is...

How to translate parts of source program to library calls without writing a full parser?

c,parsing,translation

There's a lot of parsing wrapper generators out there, chief among these SWIG (which is awesome, and horrible at the same time). If you can't use SWIG or something like existing parsers: I'd completely avoid changing the original code -- the C functions must be externally visible, anyway, so it's...

Time's Tables Quiz (Error)

c,if-statement,syntax-error,expression

Your code has various syntax errors (If instead of if, semicolon after if-condition). Additionally, your code has a logical problem where you read an int and then compare against a string. This version works and is properly indented: #include <stdio.h> int main (){ int answers_eight[] = {8,16,24,32,40,48,56,64,72,80,88,96}; int answer ;...

How to check the values of a struct from an image/binary file?

c,gcc,binaryfiles

objdump parses object files (products of the compiler), which are relocatable (not executable) ELF files. At this stage, there is no such notion as the memory address these compiled pieces will run at. You have the following possibilities: Link your *.obj files into the final non-stripped (-g passed to compiler)...

How can I align stack to the end of SRAM?

c,embedded,stm32,gnu-arm,coocox

I've found the reason: that's because stack size is actually fixed and it is located in heap (if I could call it heap). In file startup_stm32f10x*.c there is a section: /*----------Stack Configuration----------*/ #define STACK_SIZE 0x00000100 /*!< The Stack size suggest using even number */ And at then very next line:...

Counting bytes received by posix read()

c,function,serial-port,posix

Yes, temp_uart_count will contain the actual number of bytes read, and obviously that number will be smaller or equal to the number of elements of temp_uart_data. If you get 0, it means that the end of file (or an equivalent condition) has been reached and there is nothing else to...

scanf get multiple values at once

c,char,segmentation-fault,user-input,scanf

I'm not saying that it cannot be done using scanf(), but IMHO, that's not the best way to do it. Instead, use fgets() to read the whole like, use strtok() to tokenize the input and then, based on the first token value, iterate over the input string as required. A...

How to increment the value of an unsigned char * (C)

c++,c,openssl,byte,sha1

I am assuming your pointer refers to 20 bytes, for the 160 bit value. (An alternative may be text characters representing hex values for the same 160 bit meaning, but occupying more characters) You can declare a class for the data, and implement a method to increment the low order...

Disadvantages of calling realloc in a loop

c,memory-management,out-of-memory,realloc

When you allocate/deallocate memory many times, it may create fragmentation in the memory and you may not get big contiguous chunk of the memory. When you do a realloc, some extra memory may be needed for a short period of time to move the data. If your algorithm does...

Multiple definition and file management

c,arrays,compilation,compiler-errors,include

include is a preprocessor directive that includes the contents of the file named at compile time. The code that conditionally includes stuff is executed at run time...not compile time. So both files are being compiled in. ( You're also including each file twice, once in the main function and once...

Is there any way of protecting a variable for being modified at runtime in C?

c,variables,constants

You can make the result of the input be const like this: int func() { int op = 0; scanf( "%d", &op ); if( op == 0 ) return 1; else return 2; } int main() { const int v = func(); // ... } NB. Of course, there is...

Not Used Recently (NUR) Page Replacement Algorithm [closed]

java,c++,c,operating-system

Usually Page Replacement Algorithms have a buffer and pages to put into the buffer. Buffer size is fixed to a value say 4. Now we keep on adding pages into the buffer, If they are already in the buffer we ignore them and go for the next page to be...

How does this code print odd and even?

c,if-statement,macros,logic

In binary any numbers LSB (Least Significant Bit) is set or 1 means the number is odd, and LSB 0 means the number is even. Lets take a look: Decimal binary 1 001 (odd) 2 010 (even) 3 011 (odd) 4 100 (even) 5 101 (odd) SO, the following line...

Does realloc() invalidate all pointers?

c,pointers,dynamic-memory-allocation,behavior,realloc

Yes, ptr2 is unaffected by realloc(), it has no connection to realloc() call whatsoever(as per the current code). However, FWIW, as per the man page of realloc(), (emphasis mine) The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and...

Is reading from unallocated memory safe?

c

Since the behavior is undefined, the answer is undefined - or at the very least, erratic. If you get lucky and the random address is within the memory bounds of your program, it would be fine to read most likely and you'd just get random junk. If it's outside of...

Scoping rules for struct variables in GCC

c,gcc,struct,clang,scoping

As others mentioned, you're reading an uninitialized local variable and that's undefined. So, anything is legit. Having said that, there is a particular reason for this behavior: gcc reuses variables on the stack as much as it can (i.e., as long as the generated code is provably correct). You can...