We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
Hi, I am using ARM 2478 with keil/Real View Compiler. code to test the problem..
#include <LPC24xx.H> /* LPC23xx/LPC24xx definitions */ #include <stdlib.h> #include <stdio.h> #include <string.h> int main (void) { unsigned char *ptest; int *ptest2; int *nIntVector; unsigned char *ncVector; int nLocInt; size_t k, nVecLen; unsigned char *pByte; // // nVecLen = 2 * sizeof(int); //nIntVector = (int *)calloc(2,nVecLen); //ncVector = calloc(2,nVecLen); ncVector = malloc(2*nVecLen); // // Fill memory with 0x00, 0x01, 0x02….., 0x07 pByte = (unsigned char *)ncVector; for (k=0; k<nVecLen; k++) *(pByte++) = (unsigned char)k; // ptest = (unsigned char *)ncVector; *ptest++; nIntVector = (int *)ptest; nLocInt = *nIntVector; }
So the malloc start at address 0x40000010 in this example. the loop i have writes data 0 to 7 consecutively starting from address 0x40000010. Address 0x40000010 should have value 0x00 Address 0x40000011 should have value 0x01 Address 0x40000012 should have value 0x02 Address 0x40000013 should have value 0x03 Address 0x40000014 should have value 0x04 Address 0x40000015 should have value 0x05 Address 0x40000016 should have value 0x06
Ok now the problem is if the pointer nIntVector is pointing to address 0x40000011 and i am trying to retrieve the int value shoundt nLocInt be 0x04030201?? But instead i get 0x00030201... whats going on? Thanks
Ok now the problem is if the pointer nIntVector is pointing to address 0x40000011
Then you've broken your program. Your program is not allowed to do that.
To express it in more technical terms, this line from your program
nIntVector = (int *)ptest;
causes undefined behaviour, because ptest is not sufficiently aligned for a pointer to int. Whatever happens from that point onward is what you deserve to get.