PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 27, 2022

[FIXED] How to solve C6386 warning?

 April 27, 2022     c++, visual-studio, warnings     No comments   

Issue

I'm writing a simple code to read systemized data from .txt file, and got warning "C6386: Buffer overrun while writing to 'points': the writable size is 'num*8' bytes, but '16' bytes might be written". How to solve it in my case ? Code attached.

struct point {
    int x, y;
};

void main()
{
    fstream file;
    point* points;
    int num, 
        i = 0;

    file.open("C:\\Users\\Den\\Desktop\\file.txt", fstream::in);
    if (!file.is_open()) {
        cout << "No file found\n";
        exit(1);
    }
    else {
        file >> num;
        points = new point[num];
    }

    while (file >> num) {
        points[i].x = num;   // <- here
        file >> num;
        points[i].y = num;
        i++;
    }

    file.close();
}

Solution

It is just a warning but it is giving good advice. What if the file contains more than num items? The warning is telling you that should make sure you don't write past the end of the array. Specifically:

This warning indicates that the writable extent of the specified buffer might be smaller than the index used to write to it. This can cause buffer overrun. [msdn]

This code does not produce the warning (VS2019):

int x, y;
while (i < num && (file >> x >> y)) {
    points[i].x = x;
    points[i].y = y;
    i++;
}

There is still more error checking to add. What if file >> num; fails? What if num is negative ? What if points = new point[num]; fails (returns nullptr)?


Updated with full error checking:

struct point {
    int x, y;
};

void main()
{
    ifstream file("C:\\Users\\Den\\Desktop\\file.txt");
    if (!file) {
        cerr << "No file found\n";
        exit(-1);
    }

    int num;
    if (!(file >> num) || num <= 0) {
        cerr << "invalid num\n";
        exit(-1);
    }
    point *points = new point[num];
    if (!points) {
        cerr << "new failed\n";
        exit(-1);
    }
    int num_items = 0;
    while (num_items < num && file >> points[num_items].x >> points[num_items].y) {
        num_items++;
    }
    // Do some work here
    delete [] points;
}

In the future, consider using std::vector over raw array.



Answered By - Johnny Mopp
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing