C Dynamic Memory Allocation

Hi, I'm trying to figure out dynamic memory allocation in C, but I'm pretty sure my code is incorrect. I'm trying to set aside a contiguous block of memory of size in bytes of the users choosing, but the addresses I'm getting back are not sequential. Any help is appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int bytes = 0;
    int *pointer;

    printf("Please enter the amount of bytes you wish to set aside: ");
    scanf("%d", &bytes);

    pointer = malloc(bytes);

    if(pointer == NULL)
    {
        printf("Memory could not be allocated.");
    }
    else
    {
        printf("You have set aside %d bytes.\n", bytes);
        printf("The addresses of the memory are:\n");

        for(int i = 0; i < bytes; i++)
        {
            printf("%p\n", *(pointer + i));
        }
    }

    free(pointer);

    return 0;
}
printf("%p\n", *(pointer + i));
Why are you dereferencing the result?

try:
printf("%p\n", (pointer + i));
Last edited on
The addresses are now jumping by four places. Is that correct behaviour?
Yes. If you want it to jump by a byte at a time, try using char or unsigned char pointer types.
Last edited on
Okay, using char makes it look like a contiguous block of memory. Why is it though that when setting aside memory for an integer pointer, the addresses jump by four places each time? I thought that no matter what data type you used, the block of memory had to be contiguous. I understand that an integer will use four bytes of memory, but is that four bytes not stored at one memory address location?
It's because on your compiler an integer is 4 bytes long.

I thought that no matter what data type you used, the block of memory had to be contiguous.
It is still contiguous. The elements just take up more space.

but is that four bytes not stored at one memory address location?
They're stored in order.
Last edited on
So am I right in thinking that one byte is equal to one memory address and likewise, four bytes is equal to four memory addresses, each in a contiguous block?

For example:

char a =
F123

int b =
F124
F125
F126
F127

Is that right?
Yep. You got it down.
Thanks. That's clearer now.
Topic archived. No new replies allowed.