| View previous topic :: View next topic |
| Author |
Message |
www.bnp.org.uk

Joined: Tue Sep 27, 2005 1:21 pm Posts: 25 Location: UK
|
Posted: Tue Oct 25, 2005 12:27 pm Post subject: Memory Manipulation in C |
|
|
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 |
|
| Back to top |
|
 |
tedius

Joined: Fri Apr 08, 2005 4:20 pm Posts: 83 Location: Cambridge, England
|
Posted: Wed Oct 26, 2005 2:34 pm Post subject: |
|
|
You will have to cast the point first. You should then be able to use it as normal.
| Code: |
/* 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. |
|
| Back to top |
|
 |
www.bnp.org.uk

Joined: Tue Sep 27, 2005 1:21 pm Posts: 25 Location: UK
|
Posted: Thu Oct 27, 2005 1:51 pm Post subject: |
|
|
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. |
|
| Back to top |
|
 |
tedius

Joined: Fri Apr 08, 2005 4:20 pm Posts: 83 Location: Cambridge, England
|
Posted: Fri Oct 28, 2005 9:32 am Post subject: |
|
|
| 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. |
|
| Back to top |
|
 |
Gordon LXF regular

Joined: Thu Apr 07, 2005 6:01 pm Posts: 209 Location: Bradford, West Yorkshire
|
Posted: Fri Oct 28, 2005 5:05 pm Post subject: |
|
|
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 |
|
| Back to top |
|
 |
| View previous topic :: View next topic |
|