2

以下应用程序因空指针而崩溃。我想知道怎么了...

#include "stdio.h"
#include "string.h"

char* getFileData(char* fileName);
bool createShader( int shaderType, const char* shader, const char* shaderFile ) ;
void glShaderSource(int shader, int count, const char** string, const int* length);

int main(int argc, char* argv[])
{
    char* shader = getFileData("filea.csd");
    bool success = createShader(1, shader, "filea.csd");
    return 0;
}

char* getFileData(char* fileName) {
    if(!strcmp(fileName, "filea.csd"))
        return "this is the content of the file a\0";
    else if(!strcmp(fileName, "fileb.csd"))
        return "this is the content of the file b\0";
    else if(!strcmp(fileName, "filec.csd"))
        return "this is the content of the file c\0";
    else 
        return "";
}

bool createShader( int shaderType, const char* shader, const char* shaderFile ) 
{
    int shaderHandle = 122;

    glShaderSource( shaderHandle, 1, &shader, NULL ); ////This line is where it crashes.
    return true;
}

void glShaderSource(int shader, int count, const char** string, const int* length) {
}
4

3 回答 3

1

我认为检查 glCreateShader 的返回值可能是一件好事。确保它不为零。

线

delete shader

也是错误的。它可能不会在那里崩溃,但您需要使用它free来释放 malloc 分配的内存。

于 2012-06-04T03:22:08.413 回答
1

由于指针为 NULL,请尝试传递双指针。某种形式的东西

bool createShader( GLenum shaderType, const char** shader, const char* shaderFile )//<-- change 
{
    GLuint shaderHandle = glCreateShader( shaderType );

    glShaderSource( shaderHandle, 1, shader, NULL ); //<--change
    glCompileShader( shaderHandle );

    int status = 0;

    glGetShaderiv( shaderHandle, GL_COMPILE_STATUS, &status );
}

void main () {
      char* shader = strdup(getFileData("filea.csd"));
      bool success = createShader(shaderType, &shader, "filea.csd"); //<--change
      delete shader;
      return success;
}
于 2012-06-04T03:30:13.193 回答
0

我看到的一个错误是这一行:

    delete shader;

只有当着色器指向的内存是使用 new 运算符分配的时,该行才能正常工作。但是,如果我们查看您的 getFileData() 方法,我们会发现它返回的字符数组不是由 new 分配的,而是静态数据。

So the fix would be to have getFileData() return a character array that was allocated by the new operator, or better yet a std::string. Using dynamically-allocated character arrays for string handling is very error prone and not recommended.

于 2012-06-04T04:17:16.843 回答