osbourne clark
osbourne clark

Reputation: 23

Mysterious (I think) buffer over run in C

Sorry if this is a duplicate post. I am currently having an issue where I am getting a warning on this piece of code saying C6386: Buffer overrun while writing to 'titleTextPointer' but I'm fairly sure that there would be no buffer over runs (this is assuming that all titles end with '\0'):

    const char *title = "test";
    int titleLen = 0;
    while (title[titleLen] != '\0') {
        titleLen++;
    }
    WCHAR *titleTextPointer = (WCHAR *)malloc(sizeof(WCHAR) * (titleLen + 1)); //creates a new wide char list(WCHAR array) +1 for a terminating character(\0)
    if (titleTextPointer == NULL) {
        printf("error occured while locating space\n");
        return 1;
    }
    for (int i = 0; i < titleLen; i++) { //iterates through lists and transfers memory
        titleTextPointer[i] = title[i]; //actual transfer (char is 1byte, wide char is 2 bytes)
    }
    titleTextPointer[titleLen] = '\0'; //adds the last terminating value to properly use the widechar in function

code with error attached

I've tried allocating more space (+2) but the warning still pops up.

Upvotes: 2

Views: 111

Answers (1)

user9706
user9706

Reputation:

The code you posted does not exhibit any buffer overrun so I submit that your IDE is hallucinating. I don't know what WCHAR is so used wchar_t which is 4 bytes on my system. Note @ikegami's point that straight assignment might not be a correct mapping from char * to wchat_t *. Here is a minimal (non-reproducible) example:

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

int main(void) {
    const char *title = "test";
    size_t titleLen = strlen(title);
    wchar_t *titleTextPointer = malloc(sizeof *titleTextPointer * (titleLen + 1));
    if (!titleTextPointer) {
        printf("error occurred while locating space\n");
        return 1;
    }
    for (size_t i = 0; i <= titleLen; i++)
        titleTextPointer[i] = (unsigned char) title[i];
    free(titleTextPointer);
}

Upvotes: 2

Related Questions