[SOLVED] passing char buffer to functions and getting the size of the buffer

Issue

I have set the buffer to size 100.
I display the buffer in the main function where the buffer is declared.
However, when I pass the buffer to the function and get the sizeof ‘4’,
I was thinking it should be 100, as that is the size of the buffer that I
created in main.
output:
buffer size: 100
sizeof(buffer): 4

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

void load_buffer(char *buffer);

int main()
{
    char buffer[100];
    printf("buffer size: %d\n", sizeof(buffer));
    load_buffer(buffer);

    return 0;
}

void load_buffer(char *buffer)
{
    printf("sizeof(buffer): %d\n", sizeof(buffer));
}

Solution

You are using the size of the pointer to the buffer (4 bytes), rather than the size of the buffer.

In C, you have to pass the size of the buffer separately, which is part of the reason buffer overruns happen so easily and frequently.

void load_buffer(char * buffer, size_t bufSize)
{    
    ...
}

Answered By – Mitch Wheat

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.