473,903 Members | 4,843 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloc and functions

I am having an issue with malloc and gcc. Is there something wrong
with my code or is this a compiler bug ?

I am running this program:

#include <stdio.h>
#include <stdlib.h>

typedef struct pxl {
double lon, lat;
double x,y,z;
double px,py;
} pixel;
struct chn {
int index;
struct nde *node;
};

struct nde {
pixel position;
struct chn *forward;
struct chn *reverse;
int *chain_num;
int size;
};

typedef struct chn chain;
typedef struct nde node;

node *createnode( );

main()
{

node *startn;

startn = createnode( );

startn->size = 2;
startn->forward = malloc( 2 * sizeof( chain * ) );
startn->reverse = malloc( 2 * sizeof( chain * ) );

printf("sf %p\nsr %p\n\n",
startn->forward,
startn->reverse
);

printf("sf %p\nsr %p\n\n",
startn->forward,
startn->reverse
);

}

node *createnode( )
{
node *node;
node = malloc( sizeof(node) );
return node;
}

I get the following output.

sf 0x660168
sr 0x660178

sf 0xa383731
sr 0x660178

The startn->forward point changes between the two printfs despite
there being no code between them.

Jul 15 '07 #1
23 2741
raphfrk <ra*****@netsca pe.netwrites:
>
node *createnode( )
{
node *node;
node = malloc( sizeof(node) );
Just a quick glance, the above "confused me".

node? Try "node * pnode" ...

No idea if it will fix your problem.

Jul 15 '07 #2
On Jul 15, 4:09 pm, Richard <rgr...@gmail.c omwrote:
raphfrk <raph...@netsca pe.netwrites:
node *createnode( )
{
node *node;
node = malloc( sizeof(node) );

Just a quick glance, the above "confused me".

node? Try "node * pnode" ...

No idea if it will fix your problem.
Yeah, that fixed it. I have been trying to figure it out for ages
(well about 3 hours). gcc must be misinterpreting what I wanted. It
didn't give a warning though.

Thanks alot.

Jul 15 '07 #3
On Jul 15, 10:57 am, raphfrk <raph...@netsca pe.netwrote:
I am having an issue with malloc and gcc. Is there something wrong
with my code or is this a compiler bug ?

I am running this program:

#include <stdio.h>
#include <stdlib.h>

typedef struct pxl {
double lon, lat;
double x,y,z;
double px,py;
} pixel;

struct chn {
int index;
struct nde *node;
};

struct nde {
pixel position;
struct chn *forward;
struct chn *reverse;
int *chain_num;
int size;
};

typedef struct chn chain;
typedef struct nde node;

node *createnode( );

main()
'int main (void)' is better.
{

node *startn;

startn = createnode( );

startn->size = 2;
startn->forward = malloc( 2 * sizeof( chain * ) );
startn->reverse = malloc( 2 * sizeof( chain * ) );

printf("sf %p\nsr %p\n\n",
startn->forward,
startn->reverse
);

printf("sf %p\nsr %p\n\n",
startn->forward,
startn->reverse
);
The %p conversion specifier expects a void * argument, you need to
cast your arguments appropriately.
}

node *createnode( )
{
node *node;
Yuck. Using the same name for a typedef and a variable (esp. one that
is a pointer to that type) is ugly and has the potential to cause
great confusion, see below.
node = malloc( sizeof(node) );
Hint: Does sizeof apply to the typedef name or the variable name?
It's probably not what you expect.
You should also check the return value of malloc for failure.
return node;
}

I get the following output.

sf 0x660168
sr 0x660178

sf 0xa383731
sr 0x660178

The startn->forward point changes between the two printfs despite
there being no code between them.
Fix the issues mentioned above and let us know if you still have a
problem.

Robert Gamble

Jul 15 '07 #4
raphfrk <ra*****@netsca pe.netwrote in
news:11******** **************@ d55g2000hsg.goo glegroups.com:
On Jul 15, 4:09 pm, Richard <rgr...@gmail.c omwrote:
>raphfrk <raph...@netsca pe.netwrites:
node *createnode( )
{
node *node;
node = malloc( sizeof(node) );

Just a quick glance, the above "confused me".

node? Try "node * pnode" ...

No idea if it will fix your problem.

Yeah, that fixed it. I have been trying to figure it out for
ages (well about 3 hours). gcc must be misinterpreting what I
wanted. It didn't give a warning though.

Thanks alot.
It may have fixed it, but it doesn't explain it. Your call to
createnode came before the first printf. So why does the confusion
matter to the printf?

By the way, I repeated the printf more times, and each time after
the first, it prints the same values as the second printf. That
is, it doesn't change after that first time. What could possibly
be happening under the hood to get that bizarre result?

--
rzed
Jul 15 '07 #5
raphfrk <ra*****@netsca pe.netwrites:
On Jul 15, 4:09 pm, Richard <rgr...@gmail.c omwrote:
>raphfrk <raph...@netsca pe.netwrites:
node *createnode( )
{
node *node;
node = malloc( sizeof(node) );

Just a quick glance, the above "confused me".

node? Try "node * pnode" ...

No idea if it will fix your problem.

Yeah, that fixed it. I have been trying to figure it out for ages
(well about 3 hours). gcc must be misinterpreting what I wanted. It
didn't give a warning though.
Rubbish in rubbish out :-; Personally, even if it ever was "ok" I would
never have a variable with the same name as a type. A variable should
reflect the object to which it refers. In this case a pointer to a node
- hence a "pnode".
>
Thanks alot.
No probs. Glad to help. Good luck.

Ask in a gcc newsgroup here about the warnings - seems strange:

gnu.gcc.help
Jul 15 '07 #6
In article <87************ @gmail.com>, Richard <rg****@gmail.c omwrote:
....
>Rubbish in rubbish out :-; Personally, even if it ever was "ok" I would
never have a variable with the same name as a type.
This is common with structs. You frequently see code like: struct stat stat;
Of course: int int
doesn't work as well.
>A variable should reflect the object to which it refers. In this case a
pointer to a node - hence a "pnode".
Jul 15 '07 #7
On Jul 15, 11:48 am, gaze...@xmissio n.xmission.com (Kenny McCormack)
wrote:
In article <87ejj9isnb.... @gmail.com>, Richard <rgr...@gmail.c omwrote:

...
Rubbish in rubbish out :-; Personally, even if it ever was "ok" I would
never have a variable with the same name as a type.

This is common with structs. You frequently see code like: struct stat stat;
This is true but the issue is much worse with typedefs since they
share the same namespace as ordinary identifiers and thus have greater
potential for confusion.
Of course: int int
doesn't work as well.
Well that's because int is a keyword.

typedef int INT;
{
INT INT;
....
}

This "works" but like the example presented by the OP is horrible
form.

Robert Gamble

Jul 15 '07 #8
ga*****@xmissio n.xmission.com (Kenny McCormack) writes:
In article <87************ @gmail.com>, Richard <rg****@gmail.c omwrote:
...
>>Rubbish in rubbish out :-; Personally, even if it ever was "ok" I would
never have a variable with the same name as a type.

This is common with structs. You frequently see code like: struct stat stat;
Of course: int int
doesn't work as well.
I simply don't like it. More than likely it will confuse a debugger too
never mind someone maintaining your code.
Jul 15 '07 #9
rzed wrote:
raphfrk <ra*****@netsca pe.netwrote in
news:11******** **************@ d55g2000hsg.goo glegroups.com:
>>On Jul 15, 4:09 pm, Richard <rgr...@gmail.c omwrote:
>>>raphfrk <raph...@netsca pe.netwrites:

node *createnode( )
{
node *node;
node = malloc( sizeof(node) );

Just a quick glance, the above "confused me".

node? Try "node * pnode" ...

No idea if it will fix your problem.

Yeah, that fixed it. I have been trying to figure it out for
ages (well about 3 hours). gcc must be misinterpreting what I
wanted.
That's /one/ way of saying that you don't know the language.
It didn't give a warning though.
Try turning up the warnings. If you still doesn't warn, try using lint.
You are allowed to redeclare identifiers in an inner scope. It has good
uses, but pitfalls as well. You found one of the pitfalls.
It may have fixed it, but it doesn't explain it. Your call to
createnode came before the first printf. So why does the confusion
matter to the printf?
The error did not allocate sufficient space for struct nde.
Initializing that struct in the following code placed values into
unallocated space. printf probably used that space.
By the way, I repeated the printf more times, and each time after
the first, it prints the same values as the second printf. That
is, it doesn't change after that first time. What could possibly
be happening under the hood to get that bizarre result?
Writing beyond the allocated bounds of an object often has surprising
results.

--
Thad
Jul 15 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
2597
by: BekTek | last post by:
Hi.. I'm so sorry about that I've postes so many questions recently.. :) I'm still confused about the differences between malloc and operator new.. I know that when we work with class object and use operator new/delete, the ctor and dtor get called as expected, but malloc and free do not.. But Herbal Sutter mentioned in his greate book 'exceptional c++' about free storage
59
5240
by: Steve Zimmerman | last post by:
This program compiles fine, but are there any hidden dangers in it, or is it ok? Experiment 1 ################################################## #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <string.h>
36
6710
by: MSG | last post by:
The answer is neither. Use macros. #define ALLOC(size, type) ((type) *) malloc((size) * sizeof(type)) #define NEW(type, name, size) (type) * (name) = ALLOC((size), (type)) They are both type-safe and concise. Compare: NEW(int, x, 1000);
25
5097
by: H.A. Sujith | last post by:
If malloc fails what should I do? 1. Exit imediately. 2. Print an error message (or put a log entry) and exit. 3. Print an error message (or put a log entry) and continue execution (after possibly recovering from the error). Printing an error message might be difficult in a graphical environment. --
50
2885
by: Joseph Casey | last post by:
Greetings. I have read that the mistake of calling free(some_ptr) twice on malloc(some_data) can cause program malfunction. Why is this? With thanks. Joseph Casey.
12
7614
by: Anil | last post by:
Hi, Where can I get the source code that has the implementation of the below C operators/functions: malloc sizeof new strcmp strtok
68
15762
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting; some may find it off-topic or confusing. Disclaimers at end. The code samples are intended to be nearly minimal demonstrations. They are *not* related to any actual application code.
10
2615
by: Yevgen Muntyan | last post by:
Consider the following macro: #define ALLOCIT(Type) ((Type*) malloc (sizeof (Type))) The intent is to wrap raw memory allocation of N bytes into a macro which returns allocated chunk of memory to be used as a Type structure. The background: I was beaten many times (it surely is not my exclusive experience) by functions which return and accept void*. There are such functions,
71
19170
by: desktop | last post by:
I have read in Bjarne Stroustrup that using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete. But why is that a problem? I cannot see why using malloc instead of new does not give the same result.
3
3627
by: Petr Pavlu | last post by:
Hello, I have two questions how the functions should be written. I read the FAQ but didn't find any answer. If there is any please point me out. I. Cleanup code Consider I have to open file1, then make some malloc and then open file2. What is the best solution how to write the cleanup code? See my pseudo- code ideas.
0
9847
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,...
0
11283
Oralloy
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...
0
10875
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10986
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,...
0
10501
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9685
agi2029
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...
1
8049
isladogs
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...
0
5894
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...
2
4308
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.