2016-04-27 10 views
2

Что мне нужно сделать, так это отобразить изображение с использованием файла .ptm.glutSwapBuffers «Место для обнаружения нарушения доступа 0x0000000004C0F000»

Итак, я открываю файл, читаю W и H и устанавливаю RGBA для каждого пикселя. Но когда я пытаюсь показать, я получаю ошибку Нарушения доступа в glutSwapBuffers().

Вот код. Это своего рода беспорядок, потому что я пытаюсь много разных вещей, чтобы исправить это, но я начинаю думать, что каждый раз, когда я создаю новую проблему: D

Image.h

class Image { 
public: 
    Image() {}; 
    Image(int w, int h); 
    ~Image(); 
    void setPixel(int rgb, int x, int y) { 
     pixels[x + y] = rgb; 
    } 
    int setRgb(int r, int g, int b); 
    int setRgb(int r, int g, int b, int a); 
    int getPixel(int x, int y) { 
     return pixels[x + y*width]; 
    } 
    int * getPixel() { return pixels; } 
    int getWidth() { return width; } 
    int getHeight() { return height; } 
private: 
    int *pixels; 
    int width, height; 
}; 

Image.cpp

#include "Image.h" 
#include <stdlib.h> 


Image::Image(int w, int h) 
{ 
    width = w; height = h; 
    pixels = (int*)malloc(h*w); 
} 


Image::~Image() 
{ 
} 

int Image::setRgb(int r, int g, int b) 
{ 
    int rgb; 
    rgb = (r << 16) | (g << 8) | b; 
    return rgb; 
} 

int Image::setRgb(int r, int g, int b, int a) 
{ 
    int rgba; 
    rgba = (a<< 24) | (r << 16) | (g << 8) | b; 
    return rgba; 
} 

source.cpp

#include <GL\freeglut.h> 
#include <GL\GL.h> 
#include <iostream> 
#include <fstream> 
#include <string> 
#include <Windows.h> 
#include "Image.h" 

using namespace std; 

void display() 
{ 
    glClear(GL_COLOR_BUFFER_BIT); 

    Image *img = new Image(800, 500); 
    int w, h, max; //width height MaxValue 
    char *w_ = new char; //in case of the file doesn't have a comment 
    string fileModel, comment; 
    ifstream myfile("dba.ptm"); //open the file 

    if (myfile.is_open()) 
    { 
     myfile >> fileModel; 
     if (fileModel == "P7") 
     { 
      myfile >> w_; 
      if (*w_ == '#') 
       getline(myfile, comment); 
      else 
       w = atoi(w_); 
      myfile >> h; 

      int a, r, g, b, rgba; 
      myfile >> max; 
      for (int i = 0; i < w; i++) 
      { 
       for (int k = 0; k < h; k++) 
       { 
        myfile >> a; 
        myfile >> r; 
        myfile >> g; 
        myfile >> b; 
        rgba = img->setRgb(r, g, b, a); 
        img->setPixel(rgba, i, k); 
       } 
      } 
     } 
    } 
    myfile.close(); 


    glDrawPixels(img->getWidth(), img->getHeight(), GL_BGRA_EXT, GL_UNSIGNED_BYTE, img->getPixel()); 
    glutSwapBuffers(); 
} 

void init(void) 
{ 

    glClearColor(0.0, 0.0, 0.0, 0.0); 
    glShadeModel(GL_FLAT); 
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1); 
    glEnable(GL_BLEND); 
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); 


    glMatrixMode(GL_PROJECTION); 
    glLoadIdentity(); 
    glOrtho(0.0, 800.0, 0.0, 500.0, -1.0, 1.0); 
} 

int main(int argc, char** argv) 
{ 
    glutInit(&argc, argv); 
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); 
    glutInitWindowSize(800, 500); 
    glutInitWindowPosition(100, 100); 
    glutCreateWindow("PTM"); 
    init(); 
    glutDisplayFunc(display); 
    glutMainLoop(); 
    return 0; 
} 
+1

Почему вы используете 'malloc()' в C++-программе? – drescherjm

ответ

2

malloc(h*w) должен быть malloc(h*w*sizeof(int)), другие мудрый вы выделяете достаточно памяти на четверть вашего изображения.

Вы также, кажется, просачиваете весь образ каждого кадра, который быстро исчерпает доступную оперативную память. Вам нужно free и delete все, что вы malloc и new, соответственно.

Возможно, вы также захотите очистить память, которую вы выделяете для своего изображения, чтобы избежать проблем, когда установлены только некоторые из пикселей (остальные будут случайными значениями, что, вероятно, менее предпочтительно, чем, например, полная прозрачность). Вы можете сделать это с помощью memset или std::fill после malloc.

3

Извините, но у вас есть МНОГО неправильно ... :)

  • Вы используете таНос вместо new[]
  • Вы никогда free или delete ничего
  • В большинстве случаев (за исключением pixels) вам не нужно создавать вещи на куче в любом случае
  • Это pixels[x + y] = rgb;, очевидно, неверно
  • Это: char *w_ = new char; //in case of the file doesn't have a comment myfile >> w_; if (*w_ == '#') .. абсолютно НЕ делает то, что вы думаете, что делает, или что вы хотите.

Есть, вероятно, больше. :(