Memory Manipulation in C

Code junkies hangout here

Moderators: ChrisThornett, LXF moderators

Memory Manipulation in C

Postby www.bnp.org.uk » Tue Oct 25, 2005 11:27 am

Hi

I am writing a program in C and need to know how I can directly access say 1mb of memory allocated via malloc.

Within this 1mb I need to be able to read and write individual bytes and words.

Prototype: void *malloc(size_t size);

malloc returns a pointer of type void, which is a pointer that points to anything i.e. it doesn't have a type like char, short int, int etc. Apparently it is not possible to get a value at the address of a void pointer presumably because it is not known what type that value would be.

So how do I read and write bytes (chars) and words (short ints)?

Regards
User avatar
www.bnp.org.uk
 
Posts: 25
Joined: Tue Sep 27, 2005 12:21 pm
Location: UK

Postby tedius » Wed Oct 26, 2005 1:34 pm

You will have to cast the point first. You should then be able to use it as normal.

Code: Select all
/* malloc the memory */
void *pVoid = malloc(1024);

/* Cast the pointer to something we can use */
char *pChar = (char *) pVoid;

/* write to memory */
strcpy(pChar, "Hello World");

/* Read from memory */
printf("%s\n", pChar);


I hope that makes sence.
User avatar
tedius
 
Posts: 84
Joined: Fri Apr 08, 2005 3:20 pm
Location: Cambridge, England

Postby www.bnp.org.uk » Thu Oct 27, 2005 12:51 pm

Thanks. I have been reading up on pointers via google and understand what you have typed.

So now that I have *pChar, can I point it anywhere inside this allocated memory, say for example pChar = pChar + 0x100 and then *pChar = 0xff?

I want access to the memory as you would get in assembler.

Cheers.
User avatar
www.bnp.org.uk
 
Posts: 25
Joined: Tue Sep 27, 2005 12:21 pm
Location: UK

Postby tedius » Fri Oct 28, 2005 8:32 am

Yes, you can move the pointer to any point in you allocated space to read write. But you must be careful that you don't end up going off the end of memory that you have allocated.
User avatar
tedius
 
Posts: 84
Joined: Fri Apr 08, 2005 3:20 pm
Location: Cambridge, England

Postby Gordon » Fri Oct 28, 2005 4:05 pm

Because that would cause a segmentation fault, your program would immediately quit and, depending on how your system is set up, would produce a core dump to help with tracing the problem.
Violence is the last refuge of the incompetent
User avatar
Gordon
LXF regular
 
Posts: 209
Joined: Thu Apr 07, 2005 5:01 pm
Location: Bradford, West Yorkshire


Return to Programming

Who is online

Users browsing this forum: Bing [Bot] and 3 guests

cron