473,569 Members | 2,458 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help. What is the error?

The following C program segfaults on 64 bit Arch., but works fine on 32
bit.

int main()
{
int* p;
p = (int*)malloc(si zeof(int));
*p = 10;
return 0;
}

Why does it happen so?

Nov 15 '05 #1
13 1500
remove the 'cast' to malloc and
#include <stlib.h>

will work fine on all platforms

- Ravi

param wrote:
The following C program segfaults on 64 bit Arch., but works fine on 32
bit.

int main()
{
int* p;
p = (int*)malloc(si zeof(int));
*p = 10;
return 0;
}

Why does it happen so?


Nov 15 '05 #2
param wrote:
The following C program segfaults on 64 bit Arch., but works fine on 32
bit.

int main() it should really be int main(void)
{
int* p;
p = (int*)malloc(si zeof(int)); As Ravi noted, remove the cast. And make sure you have included stdlib.h.
Also, check if malloc has succeeded before using it.
*p = 10;
return 0;
}

Why does it happen so?

--
"If you would be a real seeker after truth, it is necessary that at
least once in your life you doubt, as far as possible, all things."
-- Rene Descartes
Nov 15 '05 #3
param wrote:
The following C program segfaults on 64 bit Arch., but works fine on 32
bit.

int main()
{
int* p;
p = (int*)malloc(si zeof(int));
*p = 10;
return 0;
}

Why does it happen so?


This will crash because:

1) You did not include the proper header to malloc.
2) The compiler assumes it is an unknown function that returns
the default result: an integer.
3) The compiler generates code to read an integer result from malloc
(32 bit integer) and then casts it to a 64 bit pointer. Some
bits of the pointer are lost.
4) Since you did a cast to (int *) the compiler will not warn you
about casting an integer to a pointer since it is explicitely
asked for.
5) You store the wrong address in the pointer and when you use it it
crashes.

jacob
Nov 15 '05 #4
Vimal Aravindashan wrote:
param wrote:
The following C program segfaults on 64 bit Arch., but works fine on 32
bit.

int main()


it should really be int main(void)
{
int* p;
p = (int*)malloc(si zeof(int));


As Ravi noted, remove the cast. And make sure you have included stdlib.h.
Also, check if malloc has succeeded before using it.


In addition, without the cast the compiler was *required* to complain at
you because int and pointers are not assignment compatible. If param put
in the cast to shut the compiler up then it just goes to show *why* you
should never put in a cast to shut the compiler up, you only put in
casts (or make any other change) when you understand *why* the compiler
complained and exactly what the effect will be.

The generally preferred form for calling malloc around here is
p = malloc(N * sizeof *p);
where N is the number of items you want space for. So when, as in this
case, you want space for one item you can simplify it to
p = malloc(sizeof *p);
Far less typing, the compiler is *required* to complain if you forget to
include stdlib.h (unless you have done something else really stupid) and
easier to maintain since it does not need changing if you have to change
p from int* to long* or anything else.
*p = 10;
return 0;
}

Why does it happen so?


All the advice from Ravi and Vimal was correct, although they have not
explained why, so I'll add that information.

The ANSI standard for C that was release in 1989 specified that if the
compiler has not seen a declaration for a function (or if it saw a
declaration that did not specify a return type) that it should assume
that the function returned an int. It also specified that it was
undefined behaviour (i.e. *anything* can happen) if this assumption was
made but the function actually returned something else.

On your 32 bit platform int and void* are both 32 bits and the same
method is being used to return either type so it just happens to do what
you expect.

On your 64 bit platform you probably have int as 32 bits and void* as 64
bits. So malloc returns a 64 bit pointer, but when main was compiled the
compiler assumed it would be getting a 32 bit int, so it only grabs half
of the address and then converts that in to a pointer which obviously
produces a garbage value. E.g. malloc returns a pointer with the bit
pattern of 0x1122334455667 788 but main only "sees" 0x11223344 and
converts that to address 0x0000000011223 344 which you are not allowed to
access.

It can also fail for other reasons on platforms where int and void* are
the same size, for example if addresses are returned in an address
register and integers in a data register, which does happen on some systems.

The morals of the story are *always* include the correct headers to
provide prototypes for the functions you will be using otherwise
anything might happen and don't go adding casts just to shut the
compiler up.

PS, Ravi, please put your reply *under* the text you are replying to not
above. It makes it *far* easier for people to follow the thread and is
generally considered here (and in a lot of other places) to be the
polite way to post.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #5
param wrote:

The following C program segfaults on 64 bit Arch., but works fine on 32
bit.

int main()
{
int* p;
p = (int*)malloc(si zeof(int));
*p = 10;
return 0;
}

Why does it happen so?


Another perfect example of "don't cast the return from malloc".

You have hidden the fatal error (can't implicitly convert from "int" to
"int*") with a non-fatal warning (the explicit cast).

You need to include <stdlib.h> to get malloc's prototype.

Why does it fail on one system and work on another? Because that's how
"undocument ed behavior" behaves.

As for specifics, my guess is that sizeof(int)==si zeof(void*) on the 32-bit
platform, and sizeof(int)!=si zeof(void*) on the 64-bit one.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Nov 15 '05 #6
Flash Gordon wrote:
The generally preferred form for calling malloc around here is
p = malloc(N * sizeof *p);


I'd rather write

p = malloc(N * sizeof(*p));

Yes, the parentheses are redundant. But scanning "N * sizeof *p" always
makes me think of "N * sizeof * p", which isn't good.

Of course, diff'rent strokes, and there's not much ground to gain on the
microscopic level, but still.

S.
Nov 15 '05 #7
In article <43************ ***@spamcop.net >,
Kenneth Brody <ke******@spamc op.net> wrote:
Another perfect example of "don't cast the return from malloc".


Too perfect if you ask me! Is this some kind of reverse troll?

-- Richard
Nov 15 '05 #8
Kenneth Brody wrote:
param wrote:
The following C program segfaults on 64 bit Arch., but works fine on 32
bit.

int main()
{
int* p;
p = (int*)malloc(si zeof(int));
*p = 10;
return 0;
}

Why does it happen so?
Another perfect example of "don't cast the return from malloc".

You have hidden the fatal error (can't implicitly convert from "int" to
"int*") with a non-fatal warning (the explicit cast).


The standard does not say the diagnostic has to be fatal without the
cast. With the cast no diagnostic is required for the conversion (and
not all compilers will give you a warning), although under C99 I think a
diagnostic is required due to the lack of a declaration the the removal
of implicit int from the language.
You need to include <stdlib.h> to get malloc's prototype.

Why does it fail on one system and work on another? Because that's how
"undocument ed behavior" behaves.
You mean "undefined behaviour" not "undocument ed behaviour".
As for specifics, my guess is that sizeof(int)==si zeof(void*) on the 32-bit
platform, and sizeof(int)!=si zeof(void*) on the 64-bit one.


Indeed. Although for it to "work" requires more than just the sizes
matching, it also requires the same return mechanism for pointers and
integers.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #9
Kenneth Brody wrote:
You need to include <stdlib.h> to get malloc's prototype.

Why does it fail on one system and work on another? Because that's how
"undocument ed behavior" behaves.


The code will work if the returned pointer lies in the first 4GB
virtual memory space, it will crash if it doesn't.
Nov 15 '05 #10

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

Similar topics

6
4316
by: wukexin | last post by:
Help me, good men. I find mang books that introduce bit "mang header files",they talk too bit,in fact it is my too fool, I don't learn it, I have do a test program, but I have no correct doing result in any way. Who can help me, I thank you very very much. list.cpp(main program)...
5
2129
by: xuatla | last post by:
Hi, I encountered the following compile error of c++ and hope to get your help. test2.cpp: In member function `CTest CTest::operator+=(CTest&)': test2.cpp:79: error: no match for 'operator=' in '*this = CTest::operator+(CTest&)((+t2))' test2.cpp:49: error: candidates are: CTest CTest::operator=(CTest&) make: *** Error 1
9
3012
by: YZK | last post by:
Hello. I'm not a Web developer, just a user, and I think I may have somehow messed myself up majorly. I'm not quite sure how. Right now, javascript used by websites I go to either does not work at all, or works sporadically. I'm talking about things like Hotmail, Yahoo Address Book, buttons on various sites, etc.. I'm a computer person, but...
8
5459
by: baustin75 | last post by:
Posted: Mon Oct 03, 2005 1:41 pm Post subject: cannot mail() in ie only when debugging in php designer 2005 -------------------------------------------------------------------------------- Hello, I have a very simple problem but cannot seem to figure it out. I have a very simple php script that sends a test email to myself. When I...
1
4334
by: Dave | last post by:
I am having problems accessing DTS after install SP4 and was wondering if someone could offer some advice. I installed SP4 and got the following error after it competed. Unable to write to response file 'U:\WINDOWS\setup.iss' during recording. Please ensure enough space is available on target drive. I got the error 3 times (3 pop-ups).
6
1750
by: Jax | last post by:
I have Visual Studio 2002 Standard Edition. It has been working fine up to a point and now i'm at that point. Due to the limitations of the edition i am not using any of my own .dll's and instead have a range of .cs classes doing that role for me. Does that matter? I have four errors that I just dont understand, I really need some help...
5
1794
by: Marc Violette | last post by:
<Reply-To: veejunk@sympatico.ca> Hello, I'm hoping someone can help me out here... I'm a beginner ASP.NET developper, and am trying to follow a series of exercises in the book entitled "Microsoft ASP.NET Step By Step" by Microsoft Press. When I try to display *any* ASP.NET page with a Sub() somewhere, I get the following error:
6
4971
by: James Radke | last post by:
Hello, I have a multithreaded windows NT service application (vb.net 2003) that I am working on (my first one), which reads a message queue and creates multiple threads to perform the processing for long running reports. When the processing is complete it uses crystal reports to load a template file, populate it, and then export it to a...
1
3698
by: Rahul | last post by:
Hi Everybody I have some problem in my script. please help me. This is script file. I have one *.inq file. I want run this script in XML files. But this script errors shows . If u want i am attach this script files and inq files. I cant understand this error. Please suggest me. You can talk with my yahoo id b_sahoo1@yahoo.com. Now i am...
12
2436
by: =?Utf-8?B?ZGdvdw==?= | last post by:
I designed a "contact_us" page in visual web developer 2005 express along with EW2 after viewing tutorials on asp.net's help page. Features work like they should, but I cannot figure out how to send contact info to email or data base when the "send" button is pressed. I've watched the tutorials over & over again. I just can't get it. Link:...
0
7703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7618
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...
0
7926
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. ...
1
7679
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...
0
7983
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...
0
6287
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...
0
3657
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...
0
3647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
946
bsmnconsultancy
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...

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.