Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have a function in C that is crashing my code and I'm having a hard time figuring out what is going on. I have a function that looks like this:
#define cond int
void Enqueue(cond (*cond_func)());
cond read() {
return IsEmpty(some_global); // Returns a 1 or a 0 as an int
}
Enqueue(&read);
However, when running the above, it segfaults as soon as Enqueue is called. It doesn't even execute anything inside the function. I ran gdb and it just shows it dying as soon as Enqueue is called- no statements are processed within it. Any idea what is going on? Any help would be appreciated.
Can you give more information about the code because according to my interpretation the code is working fine.I have tried this-
#define cond int
void Enqueue(cond (*cond_func)());
cond read()
{
int some_global=1;
return IsEmpty(some_global); // Returns a 1 or a 0 as an int
}
int IsEmpty()
{
return 1;
}
void Enqueue(cond (*cond_func)())
{
printf("Perfect");
return 0;
}
int main()
{
Enqueue(&read);
return 0;
}
And it is working fine.
#define cond int
was meant to be:
typedef int cond;
Although defining an alias for your function pointer might be much more reasonable here, for example:
typedef int (*FncPtr)(void);
int read() {
printf("reading...");
}
void foo(FncPtr f) {
(*f)();
}
int main() {
foo(read);
return 0;
}
This works fine:
#include <stdio.h>
#include <stdbool.h>
typedef bool cond;
void Enqueue(cond (*cond_func)(void)) {
printf("In Enqueue()...\n");
cond status = cond_func();
printf("In Enqueue, 'status' is %s\n", status ? "true" : "false");
}
bool IsEmpty(const int n) {
return true;
}
cond my_cond_func(void) {
printf("In my_cond_func()...\n");
return IsEmpty(1);
}
int main(void) {
Enqueue(my_cond_func);
return 0;
}
Your problem is likely coming from somewhere else, such as your definition of Enqueue() which you don't provide, or the fact your function is called read() and is conflicting with the more common function of that name.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This code just calculates the software delay but whenever I try running the code it throws the following errors.Thanks in advance
error: called object is not a function or function pointer
error:expected identifier or '(' before numeric constant
#include<stdio.h>
#define delay 12800
struct my_time
{
int seconds;
int minutes;
int hours;
};
void display(struct my_time *t);
void delay(void);
void update(struct my_time *t);
int main()
{
struct my_time systime;
systime.hours=0;
systime.minutes=0;
systime.seconds=0;
while (1)
{
update(&systime);
display(&systime);
}
return 0;
}
void update(struct my_time *t){
t->seconds++;
if(t->seconds==60){
t->seconds=0;
t->minutes++;
}
if(t-> minutes==60){
t->minutes=0;
t->hours++;
}
if(t->hours==24) t->hours=0;
delay();
}
void display(struct my_time *t){
printf("%02d: ", t->hours);
printf("%02d:",t->minutes);
printf("%02d\n",t->seconds);
}
void delay(void){
long int t;
for(t=0;t<delay;t++);
}
you have defined delay to be 12800. in the line below:
#define delay 12800
in preprocessor time, preprocessor pass on your code and replace each delay he finds with 12800. so you function call : delay() becomes, 12800()! this is invalid hence the error you have got.
defines are written in uppecase letters always!
e.g. use this:
#define DELAY_T 12800
You've defined a delay macro. This will replace every instance of delay in the program (except inside strings). void delay(void); becomes void 12800(void); and so on.
To avoid this, the convention is to use all caps for macros: #define DELAY 12800.
However, there's no need for a macro. Use a constant integer. const int DELAY = 12800; It effectively does the same thing, and it's safer.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am not experienced coder.Please dont judge for bad styling.I've run into an issue with the vingenere cipher
It keeps giving me segfau
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>**
int main(int argc,string argv[])
{
while (argc!=2)
{
printf("Incorrect input\n");
return 1;
}
printf("plaintext:");
string plaintext=get_string();
string num=argv[1];
int keylength=strlen(num);
for (int j=0, n=strlen(plaintext); j<n; j++)
{
char letter=plaintext[j];
if (isalpha(letter))
{
This is the reason of Segmantation Fault error.
If i don't check if num is upper or lower case,
code runs normally.
if (isupper(letter))
{
if (isupper(num))
{
printf ("%c",((((letter-65)+(num[j%keylength]-65))%26)+65));
}
else
{
printf ("%c",((((letter-65)+(num[j%keylength]-97))%26)+65));
}
}
else
{
if (isupper(num))
{
printf ("%c",((((letter-97)+(num[j%keylength]-65))%26)+97));
}
else
{
printf ("%c",((((letter-97)+(num[j%keylength]-97))%26)+97));
}
}
}
else
{
printf ("%c",letter);
}
}
printf("\n");
return 0;
}
Most likely, you meant
if (isupper(num[j % keylength))
Passing a string (really a char *) to isupper() is an undefined operation, and may produce weird effects depending on how isupper() is implemented. The GNU implementation ---
#define __ctype_lookup(__c) ((__ctype_ptr__+sizeof(""[__c]))[(int)(__c)])
#define isupper(__c) ((__ctype_lookup(__c)&(_U|_L))==_U)
--- uses a lookup table with all sorts of fun pointer math and casting under the hood, so it likely allows a char * to be passed without the compiler complaining, but it's definitely not going to produce good results. Change your if statement, and it should work better.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Could you Please provide me any example How to verify that a function X() is getting called from function Y() not from function Z()?
Using 'C' or assembly language?
Thanks in advance.
Update:02-03-2015
Suppose kernel source code there are so many drivers calling the same function, like driver source code of SPI (Serial Phepheral Interface) and GPIO (General Purpose Input Output) is calling same function say "bzero()".
void bzero(void *s, size_t n);
I am going to test SPI and GPIO driver (driver code can not be modified). For that I have written the test driver. I can only call the function exposed from my test driver.
uint8_t SPI_read_write(uint8_t byte_out, char *s) // Function 1
{
bzero(s,sizeof(struct_global1));
return byte_in;
}
uint8_t GPIO_read_write(uint8_t byte_out, char *s)// Function 2
{
bzero(s,sizeof(struct_global2));
return byte_in;
}
int main()// Test driver
{
SPI_read_write(arg1,arg2);// When I call this function from test driver it will call bzero
}
Both the finction SPI_read_write() and GPIO_read_write() function calls the "bzero" function.
I need to ensure that "bzero" is getting called at any instance from SPI_read_write() function only.
Updates 15-04-2017
I am not able to get which line is unclear? some function fun1() can be called from N number of other function. how to determine which function called fun1()?
Probably it is related to stack, link register...
There is no way to determine the name of the function that is calling your function. This is entirely by design, because functions are intended to provide an abstraction that encapsulates a computation or an activity that is independent of the invocation site. Therefore, if you want to know which function is calling your function, the caller needs to provide this information.
C99-compliant compilers provide a way to determine the name of the current function, which can be used to pass to the target function, like this:
#define X() x(__func__)
void x(const char* caller) {
printf("x() is called from %s()\n", caller);
}
void y() {
X();
}
void z() {
X();
}
The above prints
x() is called from y()
x() is called from z()
Demo.
#include <execinfo.h>
#include <stdio.h>
void print_function(void *p) {
char cmd[128];
FILE *fp;
snprintf(cmd, sizeof(cmd), "addr2line -e %s -f %p", "print_caller", p);
fp = popen(cmd, "r");
if (fp) {
char buf[128];
while (fgets(buf, sizeof(buf), fp)) {
printf("%s", buf);
}
}
}
void Y()
{
print_function(__builtin_return_address(0));
}
void X()
{
Y();
}
int main()
{
X();
return 0;
}
$ gcc -g -o print_caller print_caller.c
$ ./print_caller
X
/home/viswesn/print_caller.c:24
I would also recommend you to view the man page of BACKTRACE() which may provide you more insight on how to view the functions that were called before getting in to the current funciton.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've been preparing for a coding contest, and came across this question on the Internet:
#include <stdio.h>
void a();
void b();
void c();
int main() { a(); printf("\n"); return 0; }
void a() { b(); printf("hi "); }
void b() { c(); printf("there "); }
void c()
{
int x;
// code here and nowhere else
}
The solution is to write code that would print out "hi there" instead of "there hi" (no additional printing functions may be used and code only goes in the comment block).
Since I've done some basic assembly coding, I realized that this could be done with stack manipulation using the integer x as the base.
I tried using gdb to find the return address of the functions and then swapped the return addresses of a and b. The compiler throws a segmentation fault, and thus I assume that I haven't used the proper return address.
How do I properly calculate the offset to find the return address? Info frame command on gdb wasn't helpful, as using the stack address value given there didn't work.
I'm running this on Linux using gcc.
I am not sure if the following will count. It's portable on POSIX. Basically you change the buffer of printf before its first call and manipulate that before before it's flushed to terminal
void c()
{
static int first = 1;
if (first) {
first = 0;
char buf0[BUFSIZ];
char buf1[BUFSIZ];
setvbuf(stdout, buf0, _IOFBF, BUFSIZ);
a();
memcpy(buf1, buf0 + 6, 3);
memcpy(buf1 + 3, buf0, 6);
memcpy(buf0, buf1, 9);
buf0[8] = '\n';
fflush(stdout);
exit(0);
}
}
You will get warnings on implicitly declaring library functions memcpy and exit. It's legal on C89 though discouraged. But in your case, no trick is too dirty, I guess. You can avoid the memcpy by copy the characters manually. You can avoid exit by instead redirect stdout through freopen. You can change BUFSIZ to a large constants if the system has a strangely small buffer size (smaller than 9). There are variants of this solution that don't require you to manually insert that \n and instead let the program exit normally from main and has the printf("\n") to put that end of line
This problem cannot be solved unless you smash the stack in the same way as an attacker smashes the stack of some process.
And to smesh the stack can be done only if you know each detail of implementation of the compiler, the problem is unsolvable otherwise.
If you know the details of the compilation (the stack structure in particular) you can use the address of the local x variable in order to obtain the addres of the current frame from the stack (of FRAME_C); in each frame is the base pointer of the previous frame and modify it.
The stack looks like that:
FRAME_MAIN = RET_OS some-data
FRAME_A = RET_MAIN some-data
FRAME_B = RET_A some-data
FRAME_C = RET_B some-data(including the variable `x`)
Using the &x we can detect the position of the FRAME_C.
One solution is
to print "Hi" in function c()
Modify FRAME_B such that RET_A to become RET_MAIN
return from function c() with return
The tricky operation is 2. but if each frame has a size that is known, then we can modify the return pointer RET_A of the frame B and detect RET_MAIN something like that:
*(&x+FRAME_C_SIZE+some-small-offset1) = /* *&RET_A = */
*(&x+(FRAME_C_SIZE+FRAME_B_SIZE)+some-small-offset2). /* *&RET_MAIN */
As you can see, you need to know a lot of details about the implementation of the compiler , so this is not at all a portable solution.
Other solution would be to print "hi, there" and redirect the stdout to /dev/null. I suppose that exit() or other compiler-depedent tricks are not allowed, otherwise the problem has no meaning for a contest.
my solution is for x86/x64 and for CL compiler, but think for gcc also exist.
question only - are exist equivalent for function :
void ** _AddressOfReturnAddress();
and are equivalent for __declspec(noinline) - for tell compiler to never inline a particular function
let
void* pb - is address in void b() just after c();
and
void* pa is address in void a() just after b();
because a and b almost the same - we can assume that
(ULONG_PTR)pa - (ULONG_PTR)&a == (ULONG_PTR)pb - (ULONG_PTR)&b;
and of course stack layout in a and b must be the same. based on this and solution.
next code tested/worked with CL compiler - on both x86/x64 (windows) and with /Ox (Full Optimization) and with /Od (Disable (Debug)) - all worked.
extern "C" void ** _AddressOfReturnAddress();
void a();
void b();
void c();
int main() { a(); printf("\n"); return 0; }
__declspec(noinline) void a() { b(); printf("hi "); }
__declspec(noinline) void b() { c(); printf("there "); }
__declspec(noinline) void c()
{
void** pp = _AddressOfReturnAddress();
void* pb = *pp;
void* pa = (void*)((ULONG_PTR)&a + ((ULONG_PTR)pb - (ULONG_PTR)&b));
for (;;)
{
if (*++pp == pa)
{
*pp = pb;
*_AddressOfReturnAddress() = pa;
return;
}
}
}
Actually i developing using unit test.
But i break down my code in other form to ask for the error that i faced.
I have these declaration in my header file
typedef struct
{
void *topOfStack;
}Stack;
typedef enum {NUMBER,OPERATOR,IDENTIFIER}Token;
int operatorEvaluate(Stack *numberStack , Stack *operatorStack);
void * pop(Stack *stack);
The following is the respective source file
#include "try.h"
void *pop(Stack *numberStack)
{
Token *newToken = NUMBER;
return newToken;
}
int operatorEvaluate(Stack *numberStack , Stack *operatorStack)
{
Token *first = (Token*)pop (numberStack);
if(numberStack != operatorStack)
{
if(*first == NUMBER)
return 1;
}
return 0;
}
This is the source file that i call the functions which is main
#include "try.h"
#include <stdio.h>
int main ()
{
Stack numberStack;
Stack operatorStack;
int num;
num = operatorEvaluate(&numberStack , &operatorStack);
printf("This is the returned value: %d",num);
return 0;
}
When i tried to compile, the unit test tell me that bad memory access.
So i try to use eclipse to compile these, and windows tells that the .exe had stop working.
Hope someone can help me, i stuck for a long time...
Enable compiler warnings.
In particular, this makes zero sense:
Token *newToken = NUMBER;
That's a pointer, and you're assigning a value.
I cannot propose a fix, as I have no idea what you're doing.
That pop() function isn't touching the stack, and is returning an enum converted to a pointer. If you try to access anything through that pointer, it's going to provoke undefined behavior.
Your pop function is wrong in a few ways. You probably want it to actually pop your stack, rather than return a constant (which it isn't doing either, by the way!)...something like this:
void *pop(Stack *numberStack)
{
return numberStack->topOfStack;
}
but if you do that it'll still crash, because you never initialize your stack OR fill the topOfStack pointer.