Force compiler not to use .rodata section - pointers

Is there any way to force gcc to put
char* str = "Hello";
not in the .rodata without change this statement in
char str[] = "Hello!";
?
Ok, so better way to do this is modify the statement to char str[]. Thanks to all.

Why? Trying to change string literals leads to undefined behavior. It's evil. Consider this program:
"hello"[0] = 'y'; // Welcome to Undefined Behavior Land. Enjoy yor stay!
std::cout << "hello" << std::endl; // Could very will print "yello" now!

static char strbuf[] = "Hello";
char *str = strbuf;

How about using strdup if your platform has it, or implementing it yourself if it doesn't?
char *str = strdup("hello world");
This will allocate memory (at runtime) and copy the string literal into an appropriately sized chunk of memory which you can quite legitimately write to and modify later.
Don't forget to free() after use though.
You might be able to force GCC to put somethings in specific sections of your choosing using the __attribute__ ((section ("my_section"))) attribute, but you'll still have to modify the original source to do that so you'd be much better off doing it a "normal" way.

Related

How to work around string splitting while loading a list from a file in QT

I'm trying to create a simple "To Do list" app in QT Creator while coding the part that loads and saves the list from a file I get stuck on a problem.
If you enter a string like "Do my homework" the program threads the string as it should, but when you load the program again the save file got split in words. So it gets all the entries but each word separated ("Do", "my", "homework").
What is the solution? I tried working with 'char arrays' and 'getline' but they give me nothing but errors.
Here is my code for the save and load parts:
void MainWindow::LoadList(){
std::ifstream load_file("./data.bin");
char loader[255];
while (load_file >> loader){
QString Writer = QString::fromStdString(loader);
ui->lstTaskList->addItem(Writer);
}
}
void MainWindow::SaveList(){
std::ofstream save_file("./data.bin");
for (auto i = 0; i < ui->lstTaskList->count(); i++){
QString Saver = ui->lstTaskList->item(i)->text();
std::string saver = Saver.toStdString();
save_file << saver << std::endl;
}
}
Can anyone help me with this, please?
My thanks in advance...
The anwser was using QFile and QByteArray for me, I knew about QFile but it tries using basic "std" c++ till I learned more about QT.

Qt logical error during getting user's input from terminal via getline function and writing it into a file

Using console, I want to write the desired user's input into a file via getline function inside the wFile function and then read it. I face with logical error during Runtime; whatever I as user write doesn't type into the output terminal and it doesn't succeed more steps. Apparently fwrite function with this feature in the libraries exists, but I want to write my own code differently this way. I think I must have neglected a point. Here's the code:
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <String>
#include <cstdlib>
using namespace std;
void wFile(QString Filename)
{
QFile mFile(Filename);
QTextStream str(&mFile);
qDebug() << "what do you want to write in the desired file: ";
istream& getline (istream& is, string& str);
if (!mFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "could not open the file";
return;
}
mFile.flush();
mFile.close();
}
void read (QString Filename){
QFile nFile(Filename);
if(!nFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << "could not open file for reading";
return;
}
QTextStream in(&nFile);
QString nText = in.readAll();
qDebug() << nText;
nFile.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString nFilename ="P:/DocumentArminV.txt";
wFile(nFilename);
read(nFilename);
return a.exec();
}
Spoiler alarm: At the very end of this answer, there is a very simple recommendation for a fix.
What OP did
Concerning istream& getline (istream& is, string& str); in wFile(QString Filename):
This declares function getline() in function wFile().
This is a valid declaration concerning C++.
Concerning the sample code, I missed the respective headers. IMHO,
#include <istream> and
#include <string>
are required to make this compiling.
However, it is possible that the existing #includes include them indirectly. So, OP's code may even compile without them.
Declaring functions, which are not used as well as re-declaring functions which are already declared is somehow useless but not wrong.
To demonstrate this, I made a small sample:
#include <cstdio>
#include <istream>
#include <string>
void func()
{
puts("in func()\n");
std::istream& getline(std::istream&, std::string&);
// Even duplicated prototyping is accepted without complaints:
std::istream& getline(std::istream&, std::string&);
}
int main ()
{
func();
return 0;
}
compiles and runs perfectly.
Output:
in func()
Live Demo on coliru
What OP (probably) wanted
Using console, I want to write the desired user's input into a file via getline function inside the wFile function and then read it.
This sounds a bit confusing to me. std::getline(std::cin, ) can be used to read user input from console. May be, it's a bit bad wording only.
Assuming, the OP wanted to read input from console, obviously, declaring a function is not sufficient – it must be called to become effective:
#include <iostream>
void func()
{
std::cout << "Enter file name: ";
std::string fileName; std::getline(std::cin, fileName);
std::cout << "Got file name '" << fileName << "'\n");
}
int main ()
{
func();
return 0;
}
Output:
Enter file name: test.txt↵
Got file name 'test.txt'
Live Demo on coliru
C++ std vs. Qt
Qt is undoubtly built on top of the C++ std library. However, though it's possible it is not recommended to mix both APIs when it can be prevented (or there aren't specific reasons to do so).
Both, Qt and C++ std, are a possibility to write portable software.
Qt covers a lot of things which are provided in the std library as well but a lot of other things additionally which are not or not yet part of std. In some cases, the Qt is a bit less generic but more convenient though this is my personal opinion. IMHO, the following explains how I came to this:
std::string vs. QString
std::string stores a sequence of chars. The meaning of chars when exposed as glyph (e.g. printing on console or displaying in a window) depends on the encoding which is used in this exposing. There are lot of encodings which interprete the numbers in the chars in distinct ways.
Example:
std::string text = "\xc3\xbc";
Decoded/displayed with
Windows-1252: ü
UTF-8: ü
Based on character type of std::string, it is not possible to determine the encoding. Hence, an additional hint must be provided to decode this properly.
(AFAIK, it is similar for std::wstring and wchar_t.)
QString stores a sequence of Unicode characters. So, one universal encoding was chosen by design to mitigate the "encoding hell".
As long as the program operates on QString, no encoding issues should be expected. The same is true when combining QString with other functions of Qt. However, it becomes a bit more complicated when "leaving the Qt universe" – e.g. storing contents of a std::string to QString.
This is the point where the programmer has to provide the additional hint for the encoding of the contents in std::string. QString provides a lot of from...() and to...() methods which can be used to re-encode contents but the application programmer is still responsible to chose the right one.
Assuming that the intended contents of text should have been the ü (i.e. UTF-8 encoding), this can be converted to QString (and back) by:
// std::string (UTF-8) -> QString
std::string text = "\xc3\xbc";
QString qText = QString::fromUtf8(text.c_str());
// QString -> std::string (UTF-8)
std::string text2 = qText.toUtf8();
This has to be considered when input from std::cin shall be passed to QString:
std::cout << "Enter file name: ";
std::string input; std::getline(std::cin, input);
QString qFileName = QString::fromLocal8Bit(input);
And even now, the code contains a little flaw – the locale of std::cin might have changed with std::ios::imbue(). I must admit that I cannot say much more about this. (In daily work, I try to prevent this topic at all e.g. by not relying on Console input which I consider especially critical on Windows – the OS on which we usually deploy to customers.)
Instead, a last note about OP's code:
How to fix it
Remembering my above recommendation (not to mix std and Qt if not necessary), this can be done in Qt exclusively:
QTextStream qtin(stdin);
qtin.readline();
I must admit that I never did it by myself but found this in the Qt forum: Re: stdin reading.

c++ Occasional Dynamic Pointer Crashing

I have made a program to take in float inputs from a user to create a dynamic array (Then use those inputs with functions to find basic stuff like max,min,sum,avg but that stuff works fine so I don't think Ill include that here for the purpose of not creating a wall of code).
It works about half the time and while I have some theories about the cause I cant put my finger on a solution.
int main() {
int Counter = 0;
float *UsrIn = nullptr;
float Array[Counter];
My first thought was that the part below was the issue. My class hasn't really gone over what notation (I assume it refers to bytes so maybe scientific notation would work) to use with new that I can recall. I just tried 20 for the sake of testing and it seemed to work(probably a silly assumption in hindsight).
UsrIn = new float[(int)20];
cout << "Enter float numbers:" << endl;
cout << "Enter '9999999' to quit:" << endl;
cin >> *UsrIn; // User Input for pointer Dynamic Array
Array[Counter] = *UsrIn;
while(*UsrIn!=9999999) // User Input for Dynamic Array
{
Counter++;
UsrIn++;
cin >> *UsrIn;
Array[Counter] = *UsrIn;
}
delete UsrIn;
delete[] UsrIn;
My other thought was that maybe a pointer address was already in use by something else or maybe it was invalid somehow. I don't know of a way to test for that because the crash I occasionally get only happens when exiting the while loop after entering "9999999"
As a side note I'm not getting any warnings or error messages just a crashed program from eclipse.
Variable-length arrays are not universally supported in C++ implementations, although your compiler clearly supports them. The problem, from what you've described, is with this code:
int main() {
int Counter = 0;
float *UsrIn = nullptr;
float Array[Counter];
You're defining a variable-length array of size 0. So, although you're allocating 20 entries for UsrIn, you're not allocating any memory for Array. The intention of variable-length arrays is to allocate an array of a given size where the size is not actually known until run time. Based on your other code, that's not really the situation here. The easiest thing to do is just change the Array size to match your UsrIn size, e.g.:
float Array[20];
If you really want more of a dynamic behavior, you could use std::vector<float>
std::vector<float> Array;
...
Array.push_back(*UsrIn);

How to deal with "%1" in the argument of QString::arg()?

Everybody loves
QString("Put something here %1 and here %2")
.arg(replacement1)
.arg(replacement2);
but things get itchy as soon as you have the faintest chance that replacement1 actually contains %1 or even %2 anywhere. Then, the second QString::arg() will replace only the re-introduced %1 or both %2 occurrences. Anyway, you won't get the literal "%1" that you probably intended.
Is there any standard trick to overcome this?
If you need an example to play with, take this
#include <QCoreApplication>
#include <QDebug>
int main()
{
qDebug() << QString("%1-%2").arg("%1").arg("foo");
return 0;
}
This will output
"foo-%2"
instead of
"%1-foo"
as might be expected (not).
qDebug() << QString("%1-%2").arg("%2").arg("foo");
gives
"foo-foo"
and
qDebug() << QString("%1-%2").arg("%3").arg("foo");
gives
"%3-foo"
See the Qt docs about QString::arg():
QString str;
str = "%1 %2";
str.arg("%1f", "Hello"); // returns "%1f Hello"
Note that the arg() overload for multiple arguments only takes QString. In case not all the arguments are QStrings, you could change the order of the placeholders in the format string:
QString("1%1 2%2 3%3 4%4").arg(int1).arg(string2).arg(string3).arg(int4);
becomes
QString("1%1 2%3 3%4 4%2").arg(int1).arg(int4).arg(string2, string3);
That way, everything that is not a string is replaced first, and then all the strings are replaced at the same time.
You should try using
QString("%1-%2").arg("%2","foo");

How to get magic number of a binary file

There is a magic number associated with each binary file , does anyone know how to retrieve this information from the file?
file <file_name>
magic numbers are usually stored in (linux):
/usr/share/file/magic
also check this link, someone was trying to use libmagic to get the information in C program, might be useful if you're writing something yourself.
Use libmagic from the file package to try and sniff out the type of file if that's your goal.
There are no general "magic" numbers in binary files on unix, though different formats might define their own. The above library knows about many of those and also use various other heuristics to try and figure out the format/type of file.
The unix file command uses magic number. see the file man page for more.(and where to find the magic file )
Read this: http://linux.die.net/man/5/magic
It's complex, and depends on the specific file type you're looking for.
There is a file command which in turn uses a magic library, the magic library reads from a file found in /etc called magic (this is installation dependant and may vary), which details what are the first few bytes of the file and tells the file what kind of a file it is, be it, jpg, binary, text, shell script. There is an old version of libmagic found on sourceforge. Incidentally, there is a related answer to this here.
Hope this helps,
Best regards,
Tom.
Expounding on #nos's answer:
Example below uses the default magic database to query the file passed on the command line. (Essentially an implementation of the file command. See man libmagic for more details/functions.
#include <iostream>
#include <magic.h>
#include <cassert>
int main(int argc, char **argv) {
if (argc == 1) {
std::cerr << "Usage " << argv[0] << " [filename]" << std::endl;
return -1;
}
const char * fname = argv[1];
magic_t cookie = magic_open(0);
assert (cookie !=nullptr);
int rc = magic_load(cookie, nullptr);
assert(rc == 0);
auto f= magic_file(cookie, fname);
if (f ==nullptr) {
std::cerr << magic_error(cookie) << std::endl;
} else {
std::cout << fname << ' ' << f << std::endl;
}
}

Resources