I am trying to use a special pointer with a guaranteed invalid address with gcc. Here is what I do:
#define MY_VALUE_OK ((void*)1);
...
int* data;
...
void* d = MY_VALUE_OK;
if( data != ((void*)1) ) // compiles ok
if( data != d ) // compiles ok
if( data != MY_VALUE_OK ) // error!
printf( " %d", *data );
Any ideas?
Ideally I'd like to define this pointer as static const in a class.
BTW, this is my old code that used to compile with Microsoft Visual Studio just fine.
Does your #define include a semi-colon (like your example does)? If so that would allow the assignment to work, but the if statement would error out because after the text substitution, there would be a semi-colon inside the conditional.
You have defined a semicolon with your #define
so...
if(data != MY_VALUE_OK)
Actually turns into:
if(data != ((void*)1);)
There is an obvious error there
Your define should be:
#define MY_VALUE_OK ((void*)1)
That should fix your problem :)
Related
In the function distSigned I am assuming that l.p != vec2(0). If this isn't the case, it could break the entire shader with a hard to find bug. Is there is any way of verifying this, and throwing a runtime-error if the parameters are invalid? This would make debugging a lot easier. I know GLSL doesn't have a throw like Java, but maybe theres some kind of hack?
struct parallel {
vec2 p;
vec2 d;
};
struct pt {vec2 v;};
float distSigned(pt p, parallel l) {
vec2 l2o = fromOrigo(l);
float d = length(l2o);
return dot(p.v, l2o/d) - d;
}
Edit: I had a look at the GLSL specification and found this:
"Compile-time errors must be returned for lexically or
grammatically incorrect shaders. Other errors are reported at compile time or link time as
indicated."
I guess this means GLSL doesn't have runtime errors? If so, maybe its possible for me to implement exceptions on my own? Is there some kind of design pattern for this?
Throw a runtime error to whom? When would it be thrown? How many shader invocations would throw, and how would the receiving code receive them?
Shaders get executed whenever the GPU gets around to it, not when you run a draw call. So the time when such errors would be "thrown" could be anywhere from "when you issue the draw call" to, well, arbitrarily far into the future. So how would you receive them, and who would do the receiving?
Plus, you're executing multiple shader invocations; every vertex and every fragment get their own individual invocation. And thus, every vertex and rasterized fragment could potentially "throw" some kind of runtime error. For a scene of size and complexity, that's potentially millions of such errors. How would you handle that?
No, if you want to debug shaders, you either need a specialized tool for that or you need to do the shader equivalent of printf debugging. That is, reduce your scene to the least complexity it can be reduced to, then write output values based on whether some error condition worked out one way or the other.
Error Pixel Implementation, Webgl2:
//:ES2_AA2_MAC_DEB: My debug macro, true if positive.
//: pix_err: PIXel ERRor ( Stores Hex Error Code )
//: pix_fra: PIXel FRAgment ( fragment color )
#if( ES2_AA2_MAC_DEB > 0 ) //:///////////////////////////://
//:ASSIGN_TO_ZERO_AT_TOP_OF_FUNCTION!!!!!!!!!!!!!!!!!!!!
uint pix_err =( 0x00000000 );
#endif //:///////////////////////////////////////////////://
//: ...Later when you want to error check....
#if( ES2_AA2_MAC_DEB > 0 ) //:///////////////////////////://
if( Ax1-Ax0+uint(1) != ES2_zoo_wid ||
Ay1-Ay0+uint(1) != ES2_zoo_hig ){
//: The first error encountered puts program ://
//: into invalid state, so we want to make sure ://
//: we never override the first error tripped. ://
//: So always guard with comparison to ://
//: 0x00000000 before setting to the error color.://
if( uint(0x00000000) == pix_err ){
pix_err=( uint(0xFF9000FF) );
};;
};;
#endif //:///////////////////////////////////////////////://
... Do more code.......................................
... DONT TRY TO EXIT EARLY if error is tripped ........
... that will just turn your code into spaghetti ......
#if( ES2_AA2_MAC_DEB > 0 ) //://////////////////////////://
if( uint(0x000000) != pix_err ){
#define F_F uint(0xFF)" //://////////////////////://
pix_fra=( vec4( //://///////////////////////////://
float( ( pix_err >> 24 ) & F_F ) / 255.0
,float( ( pix_err >> 16 ) & F_F ) / 255.0
,float( ( pix_err >> 8 ) & F_F ) / 255.0
,float( ( pix_err >> 0 ) & F_F ) / 255.0
));; //://///////////////////////////////////////://
#undef F_F //://////////////////////////////////://
};;
#endif //:///////////////////////////////////////////////://
//: Now in debug mode, you can color sample the pixel ://
//: and type in the hex code to find the exact error. ://
//: Might not be helpful for minor edge cases, but ://
//: should be very helpful for gross mistakes in ://
//: your programming logic. ://
return( pix_fra );
As it says in my edit, GLSL doesn't have runtime errors. It is possible to implement however. For something like try-catch one can do this:
#define assert(array, index, line, condition) if (!(condition)) array[index] = exception(line);
struct exception {int line;};
// In use
float distSigned(pt p, parallel l, out exception[1] errors) {
assert(errors, 0, __LINE__, l.p != vec2(0));
// rest of method ..
}
To log uncaught errors, one can use certain pixel-colors that each correspond to a specific error code, and maybe a pixel palette that hides these. When a fatal error occurs it's color is output.
In debug-mode the program can then look for pixels with these colors.
Problems with this method is that the __LINE__ can be offset if the shader is being included in another and that, in webGL, shader output can't be accessed by the CPU.
Perhaps there are GLSL debugers with this functionality, I haven't tried any.
Thanks to Nicol Bolas and LJᛃ for explaining most of this.
I am storing some data in QDataStream and immediately taking the data
bool M_FILEMANAGER::readFromDataFile(QString& fileName,RADARBEAMPATTERN *radbeam)
{
// for reading from file sequence .....
QFile fin(m_folderPath +"/"+ fileName);
if (fin.open(QIODevice::ReadOnly)) {
QDataStream in(&fin);
in.device()->startTransaction();
in >> radbeam->nPoints;
qDebug()<<"nPoints : "<<radbeam->nPoints;
fin.close();
return true;
}else{
return false;
}
}
it works fine for one use but when i reuse this function i get error
segmentation fault.
thanks in advance.
1) Strange use of QIODevice::startTransaction(). Did you mean to use QDataStream:startTransaction()? You shouldn't need that at all, but if you meant to use it to check for "valid" (complete) data in the file, do it properly (although this is typically used with async devices like sockets):
int nPoints; // temp variable to hold data, assuming radbeam->nPoints is an int
QDataStream in(&fin);
in.startTransaction();
in >> nPoints;
if (in.commitTransaction() && radbeam != nullptr)
radbeam->nPoints = nPoints;
fin.close();
2) Segfault is most likely due to radbeam pointer (eg. being null), but possibly if you're trying to read corrupted data directly into the member variable nPoints. Impossible to determine cause w/out MCVE.
I am using Qt5 and errors exist from this line of codes after running sample project I found on the internet.
QFile f( "world.txt" );
if( f.open( QIODevice::ReadOnly ) ) {
QTextStream ts( &f );
Vertex v[3];
int vcount = 0;
bool allok, ok;
while( !ts.atEnd() )
{
QStringList line = QString::split( " ",ts.readLine().simplifyWhiteSpace() );
Errors are:
split is not a member of QStringList
simplifyWhiteSpace is not a member of QString
I don't know how to convert the line to work on Qt5.
Both QStringList::split() and QString::simplifyWhitespace() were functions in Qt3, and have been renamed or moved for Qt5 (which you are using according to your tags).
For QStringList::split(), the documentation says:
Use QString::split(sep, QString::SkipEmptyParts) or QString::split(sep, QString::KeepEmptyParts) instead.
Be aware that the QString::split()'s return value is a QStringList that always contains at least one element, even if str is empty.
You already changed this in your edit, so you are left with QString::simplifyWhitespace(), where the documentation says:
QString QString::simplifyWhiteSpace () const
Use simplified() instead.
How can i find a specific character in a QFile which has a text in it?
for example i have ' $5000 ' written somewhere in my file. in want to find the "$" sign so i will realize that I've reached the number.
I tried using QString QTextStream::read(qint64 maxlen) by putting 1 as the maxlen :
QFile myfile("myfile.txt");
myfile.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream myfile_stream(&myfile);
while(! myfile_stream.atEnd())
{
if( myfile_stream.read(1) == '$')
{
qDebug()<<"found";
break;
}
}
and i get "error: invalid conversion from 'char' to 'const char* "
i also tried using the operator[] but apparently it can't be used for files.
Read in a line at a time and search the text that you've read in
QTextStream stream(&myFile);
QString line;
do
{
line = stream.readLine();
if(line.contains("$"))
{
qDebug()<<"found";
break;
}
} while (!line.isNull());
The error message you've posted doesn't match the issue in your code. Possibly the error was caused by something else.
QTextStream::read returns QString. You can't compare QString and const char* directly, but operator[] can help:
QString s = stream.read(1);
if (s.count() == 1) {
if (s[0] == '$') {
//...
}
}
However reading a file by too small pieces will be very slow. If your file is small enough, you can read it all at once:
QString s = stream.readAll();
int index = s.indexOf('$');
If your file is large, it's better to read file by small chunks (1024 bytes for example) and calculate the index of found character using indexOf result and count of already read chunks.
a single char could be read with
QTextStream myfile_stream(&myfile);
QChar c;
while (!myfile_stream.atEnd())
myfile_stream >> c;
if (c == '$') {
...
}
myfile_stream.read(1) - this is not good practice, you should not read from file one byte at a time. Either read the entire file, or buffered/line by line if there is a risk for the file to be too big to fit in memory.
The error you get is because you compare a QString for equality with a character literal - needless to say that is not going to work as expected. A string is a string even if there is only one character in it. As advised - use either the [] operator or better off for reading - QString::at() const which is guaranteed to create no extra copy. You don't use it on the QFile, nor on the QTextStream, but on the QString that is returned from the read() method of the text stream targeted at the file.
Once you have the text in memory, you can either use the regular QString methods like indexOf() to search for the index of a contained character.
in want to find the "$" sign so i will realize that I've reached the
number.
It sounds to me that you're searching for the '$' symbol because you're more interested in the dollar value that follows it. In this case, I suggest reading the files line by line and running them through a QRegExp to extract any values you're looking for.
QRegExp dollarFind("\\$(\\d+)");
while(!myfile_stream.atEnd()){
QString line = myfile_stream.readLine();
if (dollarFind.exactMatch(line)){
QStringList dollars = dollarFind.capturedTexts();
qDebug() << "Dollar values found: " << dollars.join(", ");
}
}
I'm developing a program which executes a program using execvp. It needs to capture the results of the child process and parse them in the main process. It seems there is a way, using named pipes, and duping. I'm trying to hunt down a good example of this, but so far no luck. If anyone has any pointers, links and/or suggestions about this, I'd greatly appreciate it.
You don't need named pipes; unnamed pipes work just fine. Actually, often you can just use popen instead of doing the pipe/fork/dup/exec yourself. popen works like this (though your libc's implementation likely has more error checking):
FILE *popen(const char *command, const char *type) {
int fds[2];
const char *argv[4] = {"/bin/sh", "-c", command};
pipe(fds);
if (fork() == 0) {
close(fds[0]);
dup2(type[0] == 'r' ? 0 : 1, fds[1]);
close(fds[1]);
execvp(argv[0], argv);
exit(-1);
}
close(fds[1]);
return fdopen(fds[0], type);
}
This creates an unnamed pipe, and forks. In the child, it reattaches stdout (or stdin) to one end of the pipe, then execs the child. The parent can simply read (or write) from the other end of the pipe.
Can't you just use popen()?
Here is a simple example that demonstrates the use of popen to achieve your goal. Just put something more interesting than "echo" as the command :)
#include <stdio.h>
int main()
{
char buf[100];
int i = 0;
FILE *p = popen("echo \"Test\"","r");
if (p != NULL )
{
while (!feof(p) && (i < 99) )
{
fread(&buf[i++],1,1,p);
}
buf[i] = 0;
printf("%s",buf);
pclose(p);
return 0;
}
else
{
return -1;
}
}