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