cpointersstructmalloc

How do I calculate the end address of a C struct in memory?


I have the following structure in my .c file.

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

typedef struct Student {
    char* name;
    int age;
    int id;
} Student;

Student* addStudent(int age, char* name, int id) {
    Student* student = (Student*)malloc(sizeof(Student));
    if (!student) return NULL;

    printf("The base address of the student block is %p\n", student);
    printf("The ending address of the student block is %p\n", (char*)student + sizeof(Student));

    student->age = age;
    student->id = id;

    student->name = (char*)malloc(strlen(name) + 1); 
    if (!student->name) {
        free(student);
        return NULL;
    }
    strcpy(student->name, name);

    printf("A new student is created.\n");
    return student;
}

I'm trying to understand how to calculate the starting and ending address of a dynamically allocated struct in C. The starting address is clear — it's the value stored in the pointer returned by malloc.

However, I'm confused about how to calculate the ending address of the structure. I came across this line:

printf("The ending address of the student block is %p\n",
       (char*)student + sizeof(Student));

But I don't understand why (char*)student + sizeof(student) is used here. It seems to be operating on the pointer itself, not on the memory block it points to.

This line wasn’t originally mine — I found it online, but the explanation was not very clear. Could someone clarify the logic behind this and how to correctly calculate the ending address of a dynamically allocated structure in C? Thank you for your time.


Solution

  • This expression:

    (char*)student + sizeof(Student)
    

    Takes the starting address of the memory block and advances it by the number of bytes that Student occupies, resulting in a pointer to just after the Student instance.

    The cast ensures that the arithmetic is happening in bytes, as normally pointer arithmetic happens in units of the type the pointer points to. This also means that the above would have been more clearly expressed simply as:

    student + 1