Nios® V/II Embedded Design Suite (EDS)
Support for Embedded Development Tools, Processors (SoCs and Nios® V/II processor), Embedded Development Suites (EDSs), Boot and Configuration, Operating Systems, C and C++

malloc( )problem

Altera_Forum
Honored Contributor II
1,557 Views

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 ?
0 Kudos
5 Replies
Altera_Forum
Honored Contributor II
546 Views

You've missed out part of the code. Presumably the full code is: 

unsigned char * data_written; data_written = (unsigned char *)malloc(0x1000); num=sizeof(data_written); 

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.
0 Kudos
Altera_Forum
Honored Contributor II
546 Views

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
0 Kudos
Altera_Forum
Honored Contributor II
546 Views

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?
0 Kudos
Altera_Forum
Honored Contributor II
546 Views

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&#39;s what you need (or fill it with a known pattern as this code attempts to).
0 Kudos
Altera_Forum
Honored Contributor II
546 Views

To wombat: 

 

 

 

Thank you ! Now I know.
0 Kudos
Reply