Reputation: 11
I'm required to save data, which happens to be a char array of 4096 characters tops, in a specified memory address.
So here i get the memory address from a uint32_t into the void* ptrAddress
uint32_t number = 1268;
void* ptrAddress = &number;
and here i try to copy the array of As, which works! but not really, because i get some garbage in the middle
char tryArray[4096];
for(int i = 0; i < 4095; i++ ){
tryArray[i] = 'A';
}
//EDIT: added the null terminator (forgot to do that)
tryArray[4095] = '\0';
char* copy = strcpy(ptrAddress, (char*)tryArray);
printf("lets see: %s\n", copy);
output (imagine 4096 As and 'garbage' as some garbage character):
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'garbage''garbage''garbage'AAAAAAAAAAAAAAAAA
And after that i get a seg fault
What am i doing wrong? If there's anything more you need to know from the code or my intentions with it, please tell me!
Upvotes: 0
Views: 242
Reputation: 225032
You have a couple of problems.
First, this code:
uint32_t number = 1268;
void* ptrAddress = &number;
Doesn't make a pointer to memory address 1268
, like you seem to indicate you want it to. It makes a pointer to the integer where that 1268
is stored. You then overrun that storage by a lot, causing undefined behaviour, so after that it's game over.
If you want a pointer to a specific memory address:
void *ptrAddress = (void *)0x1268;
Make sure that address is legit in your environment/address space, though!
Second, strcpy
works on null-terminated strings. You should probably use memcpy
if you plan to work with a 4096 byte (non-null terminated) buffer. Note that means you can't print using printf (at least the way you're trying).
printf("%-4096s");
Should do it though.
Upvotes: 4