i have a doubt about malloc function

[code]
int main() {
unsigned char* pointer;
pointer = malloc(1);

return 0;
}
[/code]

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

Comments

  • You can access the byte at pointer+1 but the result of modifying it is [b]undefined[/b], 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 [b]only[/b] the byte(s) malloc gives you.
  • 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.
  • [color=Blue]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]. [/color]
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories