C and C++

Moderators: None (Apply to moderate this forum)
Number of threads: 28695
Number of posts: 94715

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
i have a doubt about malloc function Posted by jcpascal27 on 8 Jan 2009 at 3:28 PM
int main() {
 unsigned char* pointer;
 pointer = malloc(1);

 return 0;
}


If i call malloc the way it's shown above, will pointer[1] be a valid byte to access? or pointer[0] is the only byte i have?

the logical answer to it would be that pointer[0] is the only byte malloc gave me, because i asked to allocate one byte, but i'd like you to answer this question to know if i'm right.

thanks

Report
Re: i have a doubt about malloc function Posted by aramonkg101 on 8 Jan 2009 at 4:50 PM
You can access the byte at pointer+1 but the result of modifying it is undefined, which means that you may corrupt some other data structure, pointer or whatever else is at that address on the heap segment of memory.

What you can safely access and change is only the byte(s) malloc gives you.
Report
Re: i have a doubt about malloc function Posted by Malcolm_McLean on 10 Jan 2009 at 5:05 PM
That's right. You'll probably get away with accessing the second byte because malloc() internally rounds up blocks to even figures, usually multiples of 8 at least. However in C terms it is illegal to read or write to that memory.
Report
Re: i have a doubt about malloc function Posted by AsmGuru62 on 11 Jan 2009 at 6:05 AM
pointer[0] is only one to access. Also, a good compiler (Microsoft C/C++ as an example) will produce a run-time error (in DEBUG mode only) if you write anything into pointer[1].



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.