Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   using gdb and stacktrace ?????? (http://www.go4expert.com/forums/using-gdb-stacktrace-t14763/)

bluesky 24Oct2008 20:02

using gdb and stacktrace ??????
void function(int a, int b, int c){
char buffer1[5];
char buffer2[10];
int *r;
r = buffer1 + 12;
(*r) += 8;
int main(){
int x = 0;
x = 1;
printf("x = %d\n", x);


I am new to this community and have joined recently. I am trying to run this program and on compiling it gives warning as "assignment from incompatible pointer type". I wanted to know why this happens that is the reason behind this warning?

Also Besides i need to use a debugger such as gdb to find out why the program is outputting the current output of x=1? And how do i provide a memory dump of the stack? Also in my opinion the program should have given output as x=0 but it gave output as x=1? So how do i modify the program so that it gives the output as x=0?

bluesky ;)

xpi0t0s 25Oct2008 01:26

Re: using gdb and stacktrace ??????
The warning probably occurs on "r=buffer+12" - this is invalid because r is an int* and buffer is a char*. The reason this is a problem that may need pointing out is that buffer+12 may not do what you want; either it will evaluate to &buffer[12] which is (void*)(&buffer[0]+12), or it will evaluate to &buffer+12*sizeof(int) which is (void*)(&buffer[0]+12*sizeof int), depending on whether the compiler converts buffer to an int* before adding 12, or converts buffer+12 to an int*.

Basically when you use a pointer to a bunch of objects, the compiler assumes that (pointer+1) means the next object, not literally the address of the object the pointer is currently pointing to plus 1. So int *p=1000; p++; will increase p to 1004 if sizeof int=4; struct s { ... } *p=1000; p++; will increase p by sizeof struct s. And char *p=1000; p++; will increase p to 1001.

So by assigning a char* pointer to an int* you're immediately creating an ambiguity. Is buffer1 to be treated as an int* or a char*, and does +12 mean +12*sizeof char or +12*sizeof int? A cast will get rid of the problem, e.g. r = (int*)buffer +12; or r=(int*)(&buffer[12]);

The program prints x=1 because that's what you're telling it to do. int x=0; x=1; printf("x=%d\n",x); will print x=1. You don't need a debugger to tell you that, just RTFC. To modify the program to print "x=0" just remove "x=1;".

I think "where" is the command for printing a stack in gdb, but of course you need a core dump. Probably what you need is to step through the code rather than to get a stack. I tend to use Visual Studio so have limited experience with gdb.

All times are GMT +5.5. The time now is 19:22.