whats wrong with the code?

I need help with something in this program.

#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>

#define MSPACE 256

int page_size;
char*mem;

void *aligned_malloc(size_t size,size_t psize){
int align_mask = psize - 1;
char *ptr=(char *)malloc(size + psize);
char *aligned_ptr=ptr + psize - ((size_t)ptr & align_mask);
return aligned_ptr;
}

int main(int argc, char** argv) {
page_size = getpagesize ();
printf("pagesize=%d\n",page_size);

printf("begin allocating\n");
mem = (char*)aligned_malloc(MSPACE);
char err = mprotect((void*)mem, page_size,PROT_READ|PROT_WRITE);
if (err<0) perror("mprotect");
printf("Done allocating mem0=%lx err=%d\n",mem,err);

printf("reading mem[0]%d\n",mem[0]);
printf("writing to mem[0]:\n");
mem[0]=20;
printf("mem[0] is now %d\n", mem[0]);
printf("All done!");
}


i get this error:
mem2.c: In function 'main':
mem2.c:22: error: too few arguments to function 'aligned_malloc'
mem2.c:32:2: warning: no newline at end of file

If anyone knows whats wrong please help and if you can be as specific as possible i would appreciate it.
Is not the error message on line 22 explicit enough?
aligned_malloc is declared to take 2 parameters. you are passing 1.

no,its not.

mem = (char *ptr)aligned_malloc(MSPACE);

i changed it to that and it didnt work.

If anyone knows what i specifically have to change in the line, i would be appreciative.
Given your declaration:

1
2
3
void* aligned_malloc( size_t size, size_t psize ) {
   // ...
}


and your call to it:

 
mem = (char*)aligned_malloc(MSPACE);


please tell me what values you are passing in to size and psize.
what im trying to do with the program is to protect arbitrary memory adresses. I tried it using malloc and it didnt work so i added the aligned malloc function. All of this code was given to me by my professor and what he said i had to do was add the function and change the line in main to use aligned_malloc() instead of malloc(). I guess from what your saying i need to add size and psize,but i dont know what i have to do to do that with what im given.
What the function wants to do is allocate a piece of memory that is "size" bytes long and return a pointer to it, with the caveat that the returned pointer must be aligned on a "psize" byte boundary. ie, the address returned modulo psize must be zero.

ok,so with

mem = (char*)aligned_malloc(MSPACE);

i tired:
mem = (char*)aligned_malloc(256 + 0);

and it didnt work. any idea what im doing wrong? Im sorry to be a pain in the ass about this,but i suck at programming.
You have to pass two parameters - the amount of space you want to allocate, and the alignment, which must be a power of 2.

So if you want to allocate 100 bytes on a page boundary (page=4K, eg),
then

void* pBuf = aligned_malloc( 100, 4096 ); // 4096 = 4 * 1024 = 4K

256 + 0 is still just one parameter.
thanks bro,i got it.
Last edited on
Topic archived. No new replies allowed.