strcpy and strcat cause problems sometimes - strcpy

hello I have a code like the one below
char *str ;
strcpy(str, "\t<");
strcat(str, time);
strcat(str, ">[");
strcat(str, user);
strcat(str, "]");
strcat(str, "(");
strcat(str, baseName);
strcat(str, ") $ ");
printf("\String is now: %s\n", str);
This code seems working but when I use XCode analyse function, it says "Function call argument is an uninitialized value" and also it sometimes causes my program crash.. when I remove it, then it works fine... Whats wrong with that? Thanks

strcpy and strcat are used to copy and concatenate strings to an allocated char array.
Since str in not initilized you're writing somewhere in memory and this is bad because you're corrupting other data. It may work at that moment but sooner or later you'll program will crash.
You should allocate memory when declaring str:
char str[100];
Also, strcat is not efficient as it needs to search for the string end to know where concatenate chars. Using sprintf would be more efficient:
sprintf(str, "\t<%s>[%s](%s) $ ", time, user, baseName);
Finally, if you can't guarantee the generated string will fit the array, you'd better use snsprintf.

You don't allocate memory and you leave str uninitialized. All later writes are done through an uninitialized pointer that points "somewhere" - that's undefined behavior.
You have to allocate (and later free) memory large enough to hold the resulting string:
char *str = malloc( computeResultSizeSomehow() );
if( str == 0 ) {
// malloc failed - handle as fatal error
}
//proceed with your code, then
free( str );

This is much simpler and error-free from buffer overflows:
#define BUFFERSIZE 512
char str[BUFFERSIZE];
snprintf(str, BUFFERSIZE, "\t<%s>[%s](%s) $ ", time, user, baseName);

Related

Need help in understanding Pointers and Strings using stack and heap memory

I was trying to understand underlying process when pointers, strings and functions are combined along with heap/stack memory. I was able to understand and learn, but I ended up with two errors which I failed to find out why.
My problem lies here:
// printf("%s\n", *ptrToString); // Gives bad mem access error if heap memory used
// printf("%s\n", ptrToString); // Output is wrong if stack was used for memory, and prints some hex values instead
Can anyone explain what am I missing here ? Also, I would like to ask some feedback about my code, and suggest any improvements we can make.
Thanks
Full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define USE_STACK_MEMORY 0
char* NewString(char string[])
{
unsigned long num_chars;
char *copy = NULL;
// Find string length
num_chars = strlen(string);
// Allocate memory
#if USE_STACK_MEMORY
copy = alloca(sizeof(copy) + num_chars + 1); // Use stack memory
#else
copy = malloc(sizeof(copy) + num_chars + 1); // Use heap memory
#endif
// Make a local copy
strcpy(copy, string);
// If we use stack then it returns a string literal
return copy;
}
int main(void)
{
char *ptrToString = NULL;
ptrToString = NewString("HI");
printf("%s\n", ptrToString);
// printf("%s\n", *ptrToString); // Gives bad mem access error if heap memory used
// printf("%s\n", ptrToString); // Output is wrong if stack was used for memory, and prints some hex values instead
#if !USE_STACK_MEMORY
if ( ptrToString ) {
free(ptrToString);
}
#endif
return 0;
}
The first print reads the value where the pointer points to. It interprets this value then as a pointer to a string. This means the first value of your string will be interpreted as the address where the string would be.
The second print is wrong for stack memory because the memory you allocate with alloca is automatically freed as soon as your NewString method returns.
From the man page of alloca:
The alloca() function allocates size bytes of space in the stack frame
of the caller. This temporary space is automatically freed when the
function that called alloca() returns to its caller.

C functions returning an array

Sorry for the post. I have researched this but..... still no joy in getting this to work. There are two parts to the question too. Please ignore the code TWI Reg code as its application specific I need help on nuts and bolts C problem.
So... to reduce memory usage for a project I have started to write my own TWI (wire.h lib) for ATMEL328p. Its not been put into a lib yet as '1' I have no idea how to do that yet... will get to that later and '2'its a work in progress which keeps getting added to.
The problem I'm having is with reading multiple bytes.
Problem 1
I have a function that I need to return an Array
byte *i2cBuff1[16];
void setup () {
i2cBuff1 = i2cReadBytes(mpuAdd, 0x6F, 16);
}
/////////////////////READ BYTES////////////////////
byte* i2cReadBytes(byte i2cAdd, byte i2cReg, byte i2cNumBytes) {
static byte result[i2cNumBytes];
for (byte i = 0; i < i2cNumBytes; i ++) {
result[i] += i2cAdd + i2cReg;
}
return result;
}
What I understand :o ) is I have declared a Static byte array in the function which I point to as the return argument of the function.
The function call requests the return of a pointer value for a byte array which is supplied.
Well .... it doesn't work .... I have checked multiple sites and I think this should work. The error message I get is:
MPU6050_I2C_rev1:232: error: incompatible types in assignment of 'byte* {aka unsigned char*}' to 'byte* [16] {aka unsigned char* [16]}'
i2cBuff1 = i2cReadBytes(mpuAdd, 0x6F, 16);
Problem 2
Ok say IF the code sample above worked. I am trying to reduce the amount of memory that I use in my sketch. By using any memory in the function even though the memory (need) is released after the function call, the function must need to reserve an amount of 'space' in some way, for when the function is called. Ideally I would like to avoid the use of static variables within the function that are duplicated within the main program.
Does anyone know the trade off with repeated function call.... i.e looping a function call with a bit shift operator, as apposed to calling a function once to complete a process and return ... an Array? Or was this this the whole point that C does not really support Array return in the first place.
Hope this made sense, just want to get the best from the little I got.
BR
Danny
This line:
byte *i2cBuff1[16];
declares i2cBuff1 as an array of 16 byte* pointers. But i2cReadBytes doesn't return an array of pointers, it returns an array of bytes. The declaration should be:
byte *i2cBuff1;
Another problem is that a static array can't have a dynamic size. A variable-length array has to be an automatic array, so that its size can change each time the function is called. You should use dynamic allocation with malloc() (I used calloc() instead because it automatically zeroes the memory).
byte* i2cReadBytes(byte i2cAdd, byte i2cReg, byte i2cNumBytes) {
byte *result = calloc(i2cNumBytes, sizeof(byte));
for (byte i = 0; i < i2cNumBytes; i ++) {
result[i] += i2cAdd + i2cReg;
}
return result;
}

Tuning QDataStream

I have a program that in outline processes binary data from afile.
Code outline is the following:
QFile fileIn ("the_file");
fileIn.open(QIODevice::ReadOnly);
The file has a mix of binary and text data.
The file contents are read using QDataStream:
QDataStream stream(&fileIn);
stream.setByteOrder(QDataStream::LittleEndian);
stream.setVersion(QDataStream::Qt_5_0);
I can read the data from the QDataStream into various data types. e.g.
QString the_value; // String
stream >> the_value;
qint32 the_num;
stream >> the_numm;
Nice and easy. Overall I read the file data byte by byte until I hit certain values that represent delimiters, e.g. 0x68 0x48. At this point I then next the next couple of bytes that tell me what type of data is next (floats, Strings, ints, etc) and extract as appropriate.
So, the data is orocessed (outline) like:
while ( ! stream.atEnd() )
{
qint8 byte1 = getInt8(stream);
qint8 byte2 = getInt8(stream);
if ( byte1 == 0x68 && byte2 == 0x48 )
{
qint8 byte3 = getInt8(stream);
qint8 byte4 = getInt8(stream);
if ( byte3 == 0x1 && byte4 == 0x7 )
{
do_this(stream);
}
else if ( byte3 == 0x2 && byte4 == 0x8 )
{
do_that(stream);
}
}
}
Some of this embedded data may be compressed, so we use
long dSize = 1024;
QByteArray dS = qUncompress( stream.device()->read(dSize));
QBuffer buffer;
buffer.setData(dS);
if (!buffer.open(QBuffer::ReadOnly)) {
qFatal("Buffer could not be opened. Something is very wrong!");
}
QDataStream stream2(&buffer);
stream2.setByteOrder(QDataStream::LittleEndian);
stream2.setVersion(QDataStream::Qt_5_0);
The convenience of QDataStream makes it easy to read the data, in terms of mapping to particular types but also in handling endianess easily, but it seems to be at the expense of speed. The issues is compounded by the fact that the processing is recursive - data being read could itself contain embedded file data, which needs to be read and processed in the same way.
Is there an alternative that is faster, and so if, how then to handle Endianess the same way?
Your code looks straight forward .. recursion should not be the show stopper ...
Do you have lots of strings ? Thousands ?
stream >> string allocates memory using new what is really slow. And needs to be freed manually afterwards. Refer to the Qt Docs for operator>>(char *&s) method. This is used when reading into QStrings.
Same is true for readBytes(char *&s, uint &l) which may be called internally slowing everything down !
The QString itself will also allocate memory (twice as much as it uses 16bit encoding) what slows down further.
If you use one of these functions often, consider rewriting that code parts for directly reading into a preallocated buffer using readRawData(char *s, int len) before further processing.
Overall, if you need high performance QDataStream itself may well be the show stopper.

Finding a specific character in a file in Qt

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(", ");
}
}

C++ pointer is initialized to null by the compiler

So I've been stuck on a memory problem for days now.
I have a multi-threaded program running with c++. I initialize a double* pointer.
From what I've read and previous programming experience, a pointer gets initialized to garbage. It will be Null if you initialize it to 0 or if you allocate memory that's too much for the program. For me, my pointer initialization, without allocation, gives me a null pointer.
A parser function I wrote is suppose to return a pointer to the array of parsed information. When I call the function,
double* data;
data = Parser.ReadCoordinates(&storageFilename[0]);
Now the returned pointer to the array should be set to data. Then I try to print something out from the array. I get memory corruption errors. I've ran gdb and it gives me a memory corruption error:
*** glibc detected *** /home/user/kinect/openni/Platform/Linux/Bin/x64-Debug/Sample-NiHandTracker: free(): corrupted unsorted chunks: 0x0000000001387f90 ***
*** glibc detected *** /home/user/kinect/openni/Platform/Linux/Bin/x64-Debug/Sample-NiHandTracker: malloc(): memory corruption: 0x0000000001392670 ***
Can someone explain to me what is going on? I've tried initializing the pointer as a global but that doesn't work either. I've tried to allocate memory but I still get a memory corruption error. The parser works. I've tested it out with a simple program. So I don't understand why it won't work in my other program. What am I doing wrong? I can also provide more info if needed.
Parser code
double* csvParser::ReadCoordinates(char* filename){
int x; //counter
int size=0; //
char* data;
int i = 0; //counter
FILE *fp=fopen(filename, "r");
if (fp == NULL){
perror ("Error opening file");
}
while (( x = fgetc(fp)) != EOF ) { //Returns the character currently pointed by the internal file position indicator
size++; //Number of characters in the csv file
}
rewind(fp); //Sets the position indicator to the beginning of the file
printf("size is %d.\n", size); //print
data = new char[23]; //Each line is 23 bytes (characters) long
size = (size/23) * 2; //number of x, y coordinates
coord = new double[size]; //allocate memory for an array of coordinates, need to be freed somewhere
num_coord = size; //num_coord is public
//fgets (data, size, fp);
//printf("data is %c.\n", *data);
for(x=0; x<size; x++){
fgets (data, size, fp);
coord[i] = atof(&data[0]); //convert string to double
coord[i+1] = atof(&data[11]); //convert string to double
i = i+2;
}
delete[] data;
fclose (fp);
return coord;
}
Corrupt memory occurs when you write outside the bound of an array or vector.
It's called heap underrun and overrun (depends on which side it's on).
The heap's allocation data gets corrupted, so the symptom you see is an exception in free() or new() calls.
You usually don't get an access violation because the memory is allocated and it belongs to you, but it's used by the heap's logic.
Find the place where you might be writing outside the bounds of an array.

Resources