I have the follwing code:
#include <stdio.h>
#include <stdlib.h>
struct data {
int *ip;
};
struct data first;
struct data *current = &first;
int init()
{
int a = 222;
current->ip = &a;
printf("init :%d\n", *current->ip);
return 0;
}
void zap(int a, int b)
{
printf("current->prio: %d\n",*current->ip);
}
int main()
{
init();
zap(3,5);
return 0;
}
When I do the printf in init() I get 222 as expected. But when I do it in
zap(int a, int b) I get 5!! If I remove the arguments from zap like this:
zap()
and call it like this from main:
zap()
I get 222 printed as expected from the zap() function.
What kind of black magic is this?
JOhs 5 1674
Johs32 wrote On 03/14/06 15:02,: I have the follwing code: [snipped; see up-thread]
What kind of black magic is this?
The consequence of defective spells. If you haven't
been told already, there's a Frequently Asked Questions
(FAQ) site for comp.lang.c at http://www.c-faq.com/
.... which you should visit, because the problem you're
experiencing is covered in Question 7.5a. (If you've
already been told to read the FAQ and you haven't done
so, shame on you!)
By the way, your problem is "weird" or possibly
"wired," but not "wierd."
-- Er*********@sun .com
On Tuesday 14 March 2006 20:02, Johs32 opined (in
<dv**********@n ews.net.uni-c.dk>): I have the follwing code:
#include <stdio.h> #include <stdlib.h>
struct data { int *ip; };
struct data first; struct data *current = &first;
int init() { int a = 222; current->ip = &a; printf("init :%d\n", *current->ip); return 0; } void zap(int a, int b) { printf("current->prio: %d\n",*current->ip);
}
int main() { init(); zap(3,5); return 0;
}
When I do the printf in init() I get 222 as expected. But when I do it in zap(int a, int b) I get 5!! If I remove the arguments from zap like this:
zap()
and call it like this from main:
zap()
I get 222 printed as expected from the zap() function.
What kind of black magic is this?
No black magic, just poor programming (or poor understanding thereof).
In `init` you assign an address of a local variable to your pointer.
This local variable no longer exists once you exit `init`. Therefore,
dereferencing the pointer in `zap` reads memory that does not even
necessarily exist (as far as C Standard is concerned).
The difference you observe with or without parameters to `zap` is due to
the fact that your implementation seems to be using the stack, and the
same stack area for both functions. So, if you have no parameters it
does not bother changing the memory once occupied by `a` in `init`, but
with parameters to `zap`, one of them gets the honour of occupying the
same spot.
I suggest you go back and study local variables in C.
--
BR, Vladimir
Did YOU find a DIGITAL WATCH in YOUR box of VELVEETA?
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Johs32 wrote: I have the follwing code:
#include <stdio.h> #include <stdlib.h>
struct data { int *ip; };
struct data first; struct data *current = &first;
int init() { int a = 222; current->ip = &a; printf("init :%d\n", *current->ip); return 0; } void zap(int a, int b) { printf("current->prio: %d\n",*current->ip);
}
int main() { init(); zap(3,5); return 0;
}
When I do the printf in init() I get 222 as expected. But when I do it in zap(int a, int b) I get 5!!
- From reviewing your code, I can see why.
[snip]
What kind of black magic is this?
There is no "black magic" involved. You just invoked "undefined
behaviour" by doing something incorrect in your code, that's all.
Tell me, at the printf() statement in init(), what does *current->ip
point to? What does it point to at the printf() statement in zap()? Is
there anything special about the object that *current->ip points to at
the point you get this odd behaviour?
Here's a hint: Unless you specify that the variable is "static",
variables defined within a function are only guaranteed to be available
/within/ the function that they were defined in, and they only last
until the end of the function. After that, any reference to them invokes
"undefined behaviour".
HTH
- --
Lew Pitcher, IT Specialist, Corporate Technology Solutions,
Enterprise Technology Solutions, TD Bank Financial Group
(Opinions expressed here are my own, not my employer's)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iD4DBQFEFyZgagV FX4UWr64RArITAJ 9wGtlihwpr7Bif8 sOBF00/RvcfsQCYwWnd
b0lqTaSCbJvuioz W1KJnkw==
=5WY1
-----END PGP SIGNATURE-----
Lew Pitcher wrote: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1
Johs32 wrote: I have the follwing code:
#include <stdio.h> #include <stdlib.h>
struct data { int *ip; };
struct data first; struct data *current = &first;
int init() { int a = 222; current->ip = &a; printf("init :%d\n", *current->ip); return 0; } void zap(int a, int b) { printf("current->prio: %d\n",*current->ip);
}
int main() { init(); zap(3,5); return 0;
}
When I do the printf in init() I get 222 as expected. But when I do it in zap(int a, int b) I get 5!!
- From reviewing your code, I can see why. [snip]
What kind of black magic is this?
There is no "black magic" involved. You just invoked "undefined behaviour" by doing something incorrect in your code, that's all.
Tell me, at the printf() statement in init(), what does *current->ip point to? What does it point to at the printf() statement in zap()? Is there anything special about the object that *current->ip points to at the point you get this odd behaviour?
I see your point. I have now moved "a" outside of the function:
int a = 222;
struct data first;
struct data *current = &first;
and changed init() to:
int init()
{
current->ip = &a;
printf("init :%d\n", *current->ip);
return 0;
}
And I know get the correct print form zap.
"Johs32" <df***@dsf.co m> wrote in message
news:dv******** **@news.net.uni-c.dk... I have the follwing code:
#include <stdio.h> #include <stdlib.h>
struct data { int *ip; };
struct data first; struct data *current = &first;
int init() { int a = 222; current->ip = &a; printf("init :%d\n", *current->ip); return 0; } void zap(int a, int b) { printf("current->prio: %d\n",*current->ip);
}
int main() { init(); zap(3,5); return 0;
}
When I do the printf in init() I get 222 as expected. But when I do it in zap(int a, int b) I get 5!! If I remove the arguments from zap like this:
zap()
and call it like this from main:
zap()
I get 222 printed as expected from the zap() function.
What kind of black magic is this?
JOhs
After returning from init(), current->ip points to an address that is now
out-of-scope.
(it was set to the address of variable 'a', which was local to init() now no
longer exists).
Anything can happen when you try to dereference it. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: vool |
last post by:
Hi all,
I've got a really wierd problem here.
When I access a web page that adds information to a database on a PC running
XP Pro it works as it should.
When I access the same page from a PC running XP Home I get a ' Internal
server error - page cannot be dispalyed' message.
|
by: Markus Fischer |
last post by:
Hi,
I'm experiencing a wierd problem with IE 6 in Windows with two
_slightly_ different Version.
Give the following HTMl-Code, ideally the output of offsetTop should be
"105"; a few pixel plus minus would still be ok, whyever.
I've tested this successfully on 6.0.2800.1106 on a german W2KPro
machine, also with 6.0.2800.1106 on a german XPPro machine.
|
by: cody |
last post by:
I have a OOP problem with the well known pattern where objects containing an
object which represents a list of subobjects. Now my problem is that the
ctor of a subobject indirectly calls the property in Foo which returns the
BarList, since to this time the ctor of BarList did not returned yet, the
reference "list" is still null and so the next call
to the property tries to initialize BarList again!
I know there are several ways to solve...
|
by: Dean |
last post by:
PageOne.aspx has an image control. The imageURL of the image control points
to ImagePump.aspx.
ImagePump.aspx gets a bitmap out of a SQLServer database, puts in into a
bitmap object and does a:
myImage.save(response.outputstream, ImageFormat.jpeg).
This code works however, on this page I refer to a sessionvariable that is
accessable from all of my other pages. But that session variable is not
|
by: Flores Eken |
last post by:
Hi group,
I've made my own implementation of the Time Tracker ASP.NET
starterkit, added several features and extra's, works like a charm.
Now i've uploaded it to my hosting account, to be able to share it
with my co-workers, so far no problem... still works like a charm.
Until I tried to access the application over HTTPS (SSL).. logon works
great, main form is displayed and everything looks good, until a
button is pressed that performs...
| |
by: Shane Bishop |
last post by:
I've been fighting with the Page_Load event firing twice.
I looked through this user group and saw several other people having
similar problems.
There were various reasons for it:
AutoEventWireup="true" instead of AutoEventWireup="false"
Spyware software
And having your events all wired wrong
I had done everything to my machine, stripped it down to just have
..NET on it and I was still having this problem until...
|
by: Michael |
last post by:
Hi,
I found a wierd problem in DataGrid.
If I set DataGrid's DataSource to empDataSet1 at designtime,
then I can never change its DataSource at runtime, e.g., in the
Button1_Click event procedure:
DataGrid1.DataSource = dataView1;
DataGrid1.DataBind();
But if I clear DataGrid's DataSource property at designtime,
|
by: Tom |
last post by:
This is very strange: I have a Windows Form with a Panel on it. In that
panel I dynamically (at run time) create some labels, as so:
for i=1 to x
dim ctlNew as New Label()
with ctlNew
.Name="Whatever" & trim(cstr(i))
.Text=.Name
.Visible=True
... etc etc etc ...
|
by: desktop |
last post by:
I am confused about the use of the template parameter "E" in the below
class. Since when is it allowed to use these parameters like "E(1)" and
what does it mean (where can I read more about this kind of use)?
template <typename E>
class Mytest {
public:
Mytest(int n) {
s = E(0);
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |