【问题标题】:Getting Segmentation Fault in nvidia-340-updates在 nvidia-340-updates 中出现分段错误
【发布时间】:2015-07-04 19:08:57
【问题描述】:

我有点在为 C++ 学习 SDL OpenGL(我的错误),我不得不将它移植到 C。因为 C++ 对我来说有点令人困惑(顺便说一句。是的,我可以在网上搜索替代函数)。所以运行它给了我一个错误,似乎在 NVIDIA 驱动程序中(顺便说一句。卡是 GeForce 105m)。这是我的错还是驱动程序中的错误(我认为是我的错,因为它上面的每个游戏似乎都运行良好) ?

这是 gdb 回溯:

Program received signal SIGSEGV, Segmentation fault.
strlen () at ../sysdeps/x86_64/strlen.S:106
106 ../sysdeps/x86_64/strlen.S: No such file or directory.
(gdb) bt
#0  strlen () at ../sysdeps/x86_64/strlen.S:106
#1  0x00007ffff59cf699 in ?? ()
   from /usr/lib/nvidia-340-updates/libnvidia-glcore.so.340.76
#2  0x00007ffff59d1d89 in ?? ()
   from /usr/lib/nvidia-340-updates/libnvidia-glcore.so.340.76
#3  0x0000000000401f86 in compileShader ()
#4  0x0000000000401ca6 in compileShaders ()
#5  0x00000000004018b9 in initShaders ()
#6  0x0000000000401a02 in Initilize ()
#7  0x00000000004015ae in main ()

这里是 compileShader 函数(我不会写整个代码,因为它太长了;),如果你愿意,我仍然可以发布它):

void compileShader(char* filePath, GLuint id) {

    //Open the file
    FILE *shaderFile = fopen(filePath, "rw");
    if (shaderFile == NULL) {
    char *str;
    sprintf(str,"Failed to open %s", &filePath);
        fatalError(str);
    }
    //File contents stores all the text in the file
    char * fileContents = "";
    char symbol;
    //Get all the lines in the file and add it to the contents
    while ((symbol = fgetc(shaderFile)) != EOF ) {
        fileContents += symbol;
    }
    fileContents += EOF;
    fclose(shaderFile);
    glShaderSource(id, 1, &fileContents, NULL);
    glCompileShader(id);
    GLint success = 0;
    glGetShaderiv(id, GL_COMPILE_STATUS, &success);

    if (success == GL_FALSE)
    {
        glDeleteShader(id);
    char *str;
    sprintf(str,"Shader %s failed to compile", filePath);
        fatalError(str); //Don't worry this just prints out the error
    }
}

【问题讨论】:

  • fileContents += symbol; - fileContentschar*;不是std::string;这不是 C++;这不会将文件内容“添加”到任何内容。您正在将指针地址移动到无效值;不附加数据。没有任何读取数据存储在任何地方。随后使用所述指针自然会调用未定义的行为
  • 谢谢,我以为不是C,所以我换了。
  • 我明白这一点。我在上一条评论中的意思只是 char* in C 不会像 std::string 或其他类似容器在 C++ 中那样表现。它们几乎在所有方面都存在根本不同。您的端口的那部分只是损坏了。关于如何使用 C 结构加载具有文件内容的动态大小的缓冲区,在 SO 和网络上有很多示例。我会敦促你找到他们。更好的是,学习 C++ 并按原样使用原始库。
  • 这里有一组用于从文件加载着色器的 C 函数的要点:gist.github.com/datenwolf/f108f2ed4085f3840457

标签: c linux opengl glsl nvidia


【解决方案1】:

这是您代码中的错误。

您提供给驱动程序的fileContents 指针完全无效,因此驱动程序在取消引用此指针时崩溃。

您在 C 中没有原生字符串数据类型,您只需使用 char 的数组即可。 C 不会为你做任何类型的内存管理。因此,char 指针上的 += 运算符不会进行字符串连接。这只是指针算术。您的内存中只有一个 emoty 字符串,并且 fileContent 最初指向它。按行

fileContents += symbol;

您将该指针增加symbol 的数值,因此指向该空字符串之外的一些内存。

我不想听起来粗鲁,所以请不要误会我的意思。但我真的建议你先学习你想使用的编程语言,然后再继续使用 OpenGL。

【讨论】:

    猜你喜欢
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多