strtok doesn't tokenize the char* neither is this program printing any data

197 Views Asked by At

This is the program:

#include <QPoint>
#include <string.h>
#include <QList>
using namespace std;
#include <iostream>

int main(int argc, char *argv[])
{
    int y = 14;
    char * str = new char [y];
    str = "23,211,23,211";

    char *pch;
    std::cout << "\nSplitting string into tokens: \n" << str;

    pch = strtok (str,",");
    QList <int> p;
    while (pch != NULL)
    {
        std::cout << "\npch:" << pch;
        p.push_back (atoi (pch));
        pch = strtok (NULL, ",");
    }


    std::cout << "Length of p " <<  p.length() << std::endl;

    QPoint first;
    first.setX               (p[0]);
    first.setY               (p[1]);

    QPoint second;
    second.setX              (p[2]);
    second.setY              (p[3]);

    return 0;
}

The output is: enter image description here

What point am I missing?

1

There are 1 best solutions below

0
On BEST ANSWER

There are several bugs in your code. First of all there is a memory leak. At first you allocated dynamically memory and its address was assigned to pointer str

char * str = new char [y];

And then you reassigned the pointer with the address of string literal "23,211,23,211"

str = "23,211,23,211";

So the address of the allocated memory is lost.

String literals may not be modified neither in C++ nor in C while function strtok tries to change the string passed to it as an argument. So the program has undefined behaviour.

I think you mean the following.

char * str = new char [y];
strcpy( str, "23,211,23,211" );

Also in general case the length of p can be equal to zero. So you may not use the subscript operator with p without checking that it has a non-zero length.

Instead of C function strtok you could use string stream std::istringstream declared in header <sstream>.

Take into account that you should use header <cstring> instead of <string.h> in C++.

#include <cstring>