memset & alignment

D

dragoncoder

Please have a look at the following code snippet.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void* func ( int i )
{
void* ptr = malloc(sizeof(int));
memset(ptr, i, sizeof(int));
return ptr;
}

int main()
{
int i = 123;
int res = *((int*)func(i));
printf("i is %d\n", res);
return 0;
}

[l34@premier rnd]$ gcc p1.c
[l34@premier rnd]$ ./a.out
i is 2071690107

I don't understand what the problrm is, as I was expecting 123 to get
printed. Can somebody tell why this garbage is being printed.

Thanks.
 
C

Chris Dollin

dragoncoder said:
Please have a look at the following code snippet.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void* func ( int i )
{
void* ptr = malloc(sizeof(int));
memset(ptr, i, sizeof(int));

You want to set each byte of the int-sized object at *ptr to
i? OK. Seems a bit strange, but you know best.
return ptr;
}

int main()
{
int i = 123;
int res = *((int*)func(i));
printf("i is %d\n", res);
return 0;
}

[l34@premier rnd]$ gcc p1.c
[l34@premier rnd]$ ./a.out
i is 2071690107

I don't understand what the problrm is, as I was expecting 123 to get
printed.

Bad expectation.

If `sizeof int` is 4 and there are 8 bits-per-byte (likely guesses), you've
set `res` to

(123 << 24) | (123 << 16) | (123 << 8) | 123

which by an amazing coincidence prints as 2071690107.

Surely surely surely you would have been better with

int *func( int i )
{
int *ptr = malloc( sizeof (*ptr) );
*ptr = i;
return ptr;
}
??
 
N

Neroku

dragoncoder ha escrito:
Please have a look at the following code snippet.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void* func ( int i )
{
void* ptr = malloc(sizeof(int));
memset(ptr, i, sizeof(int));
return ptr;
}

int main()
{
int i = 123;
int res = *((int*)func(i));
printf("i is %d\n", res);
return 0;
}

[l34@premier rnd]$ gcc p1.c
[l34@premier rnd]$ ./a.out
i is 2071690107

I don't understand what the problrm is, as I was expecting 123 to get
printed. Can somebody tell why this garbage is being printed.

Thanks.

memset(ptr, i, n) sets each byte of n bytes pointed by ptr to i.
If n is 4, what you get pointed by ptr is:

01111011 01111011 01111011 01111011

123(decimal) = 01111011(binary)

which is 2071690107 in decimal.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top