char string1[] = "dog";
char *string2 = string1 strlen(string1) 1;
printf("address of string1: %p\n", string1);
printf("address of string2: %p\n", string2);
string2 = malloc(sizeof(char)*4);
string2[0] ='c';string2[1] ='a';string2[2] ='t';string2[3] ='\0';
printf("address of string2: %p\n", string2);
address of string1: 000000000061FE14
address of string2: 000000000061FE18
address of string2: 0000000000AD4D50
I want to make a 'cat' string at a memory location 0x61FE18, right after "dog\0"
Even though I've managed to successfully get the desired memory location of string2, the malloc function reassigns the location. I want the "cat" array to start at 0x61FE18 but malloc reassigns it to 0xAD4D50
Is there a way to allocate array to a desired starting location?
CodePudding user response:
you mean something like this?
unsigned char *data = malloc(1000);
if (data) {
strcpy((char*)data, "cat"); // `data` points to "cat" followed by garbage
strcpy((char*)data 4, "dog"); // `data` points to "cat\0dog" garbage
(int*)(data 24) = 0x01020304; // `data` points to "cat\0dog\0XXXXXXXXXXXXXXXX\1\2\3\4"
// depending on endianness and sizeof int
free(data);
}
CodePudding user response:
How do you create an array in a specific memory location? C
Is there a way to allocate array to a desired starting location?
No standard way.