Forum Discussion
Altera_Forum
Honored Contributor
21 years agomalloc( )problem
Hello :
data_written = (unsigned char *)malloc(0x1000); num=sizeof(data_written); The size of data_written should be 0x1000,But use the function sizeof,the num is 4 . I have see the memory only 00 00 00 00 4 byte. Why ?5 Replies
- Altera_Forum
Honored Contributor
You've missed out part of the code. Presumably the full code is:
So data_written is a pointer, and pointers are 32 bits on Nios II - four times the size of a char. So sizeof is returning the correct value.unsigned char * data_written; data_written = (unsigned char *)malloc(0x1000); num=sizeof(data_written); - Altera_Forum
Honored Contributor
This is a fundamental C question, and I think you should go and invest in a copy of Kernighan and Ritchie "The C Programming Language". On page 135 it states
<div class='quotetop'>QUOTE </div> --- Quote Start --- C provides a compile-time unary operator called sizeof that can be used to compute the size of any object. The expressions sizeof onject and sizeof(type name) yield an integer equal to the size of the specified object or type in bytes.[/b] --- Quote End --- i.e. in your code it will return the sizeof the type of data_written, which I assume is an unsigned char* given your cast. That is indeed 4 bytes on the Nios architecture - Altera_Forum
Honored Contributor
To
the below code is in the memtest.c data_written = (void*)alt_uncached_malloc(0x1000); data_read = (void*)alt_uncached_malloc(0x1000); /* Fill write buffer with known values */ for (pattern = 1, offset = 0; offset < sizeof(data_written); pattern++, offset+=4) { IOWR_32DIRECT((int)data_written, offset, pattern); } /* Fill write buffer with known values */ Fill the write buffer But if the sizeof(data_written) is only 4 ,the for sentence do what? and after malloc( ) the content in the location of memory is random number? - Altera_Forum
Honored Contributor
It looks as though there is a bug in memtest.c here. Please replace sizeof(data_written) with 0x1000 for correct behaviour.
The C standard says that the contents of memory returned with malloc is undefined. Some systems zero it for you, but some do not. You should use memset to zero it yourself if that's what you need (or fill it with a known pattern as this code attempts to). - Altera_Forum
Honored Contributor
To wombat:
Thank you ! Now I know.