Same address but different string - c++

Below results show two same string pointer have different value.
Why?
v8::String::Utf8Value just gives its string member, see https://v8docs.nodesource.com/node-0.8/d4/da0/v8_8h_source.html#l01286
#include <nan.h>
#include <string>
NAN_METHOD(Print) {
Nan::MaybeLocal<v8::String> maybeString = Nan::To<v8::String>(info[0]);
if (maybeString.IsEmpty() == false) {
v8::Local<v8::String> str = maybeString.ToLocalChecked();
char *ptr = *v8::String::Utf8Value(info.GetIsolate(), str);
printf("string %s\n", *v8::String::Utf8Value(info.GetIsolate(), str));
printf(" %s\n", ptr);
printf("ptr %p\n", *v8::String::Utf8Value(info.GetIsolate(), str));
printf(" %p\n", ptr);
printf("ptr %p\n", (char *)*v8::String::Utf8Value(info.GetIsolate(), str));
printf(" %p\n", (char *)ptr);
printf("string %s\n", (char *)*v8::String::Utf8Value(info.GetIsolate(), str));
printf(" %s\n", (char *)ptr);
}
}
NAN_MODULE_INIT(Init) {
Nan::Set(target, Nan::New("print").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(Print)).ToLocalChecked());
}
NODE_MODULE(myaddon, Init);
Result of info[0]='hello world':
string hello world
�AZ
ptr 0x65a4140
0x65a4140
ptr 0x65a4140
0x65a4140
string hello world
�AZ

printf("string %s\n", *v8::String::Utf8Value(info.GetIsolate(), str));
Here, you create a new object of type v8::String::Utf8Value. It's a temporary object. As soon as this statement completes, it will no longer exist. This is fine, but this is not:
char *ptr = *v8::String::Utf8Value(info.GetIsolate(), str);
printf(" %s\n", ptr);
After the first line of code executes, the v8::String::Utf8Value no longer exists. So the ptr doesn't point to anything. (If you think it does, explain how you would free the memory it points to.) So you can't access it later, but your printf does.

Related

CUDA cudaMemcpu Segmentation fault when copying array of object pointers

I am trying to move an array of pointers to the device, where each pointer is pointing to a class object. However, I get a Segmentation fault at the line using cudaMemcpy. I am trying to follow the lines used in this post.
main.cu
#include "testclass.cuh"
#include <iostream>
__global__ void printtest(Test* test){
printf("HELLO FROM CUDA\n");
printf("CUDA1 : %i\n", test->hello);
Test test2(6);
printf("CUDA2 : %i\n", test2.hello);
printf("BYEEE FROM CUDA\n");
}
int main(){
printf("hello\n");
Test* test = new Test(512);
printf("CPU : %i\n", test->hello);
Test* devtest;
cudaMalloc(&devtest, sizeof(Test));
cudaError_t err = cudaMemcpy(devtest, test, sizeof(Test), cudaMemcpyHostToDevice);
if (err != cudaSuccess) {
fprintf(stderr, "Error %s at line %d in file %s\n",
cudaGetErrorString(err), __LINE__-3, __FILE__);
}
printtest<<<1, 1>>>(devtest);
cudaDeviceSynchronize();
printf("hello2\n");
Test** test3 = new Test*[2];
test3[0] = new Test(12299);
test3[1] = new Test(234923);
printf("CPU : %i\n", test3[0]->hello);
Test** devtest3;
cudaMalloc(&devtest3, 2*sizeof(Test*));
printf("CPU2\n");
err = cudaMemcpy(devtest3[0], test3[0], sizeof(Test), cudaMemcpyHostToDevice);
if (err != cudaSuccess) {
fprintf(stderr, "Error %s at line %d in file %s\n",
cudaGetErrorString(err), __LINE__-3, __FILE__);
}
printf("CPU3\n");
printtest<<<1, 1>>>(devtest3[0]);
cudaDeviceSynchronize();
}
testclass.cu
#include "testclass.cuh"
__host__ __device__ Test::Test(int in){
hello = in;
}
testclass.cuh
class Test {
public:
int hello;
__host__ __device__ Test(int);
};
Solved it using #molbdnilo 's comment.
main.cu
...
printf("hello2\n");
Test** test3 = new Test*[2];
test3[0] = new Test(12299);
test3[1] = new Test(234923);
printf("CPU : %i\n", test3[0]->hello);
Test* devtest3[2];
cudaMalloc(&devtest3[0], sizeof(Test));
printf("CPU2\n");
err = cudaMemcpy(devtest3[0], test3[0], sizeof(Test), cudaMemcpyHostToDevice);
if (err != cudaSuccess) {
fprintf(stderr, "Error %s at line %d in file %s\n",
cudaGetErrorString(err), __LINE__-3, __FILE__);
}
printf("CPU3\n");
printtest<<<1, 1>>>(devtest3[0]);
cudaDeviceSynchronize();
...

Why fprintf() function in my code don't working properly?

First fprintf() works as it has to work, but second output whole nonsense
#include <string>
int main()
{
FILE* f;
fopen_s(&f, "text.txt", "w");
std::string name = "hello";
int area = 123;
char ch = 'i';
fprintf(f, "abc"); // OK
fprintf(f, "|%-12s |%-5c |%-9d |", name.c_str(), area, ch); // not OK
}
The %s format specifier expects a null-terminated array of char, not std::string. Thus the fprintf's behavior is undefined.
Use:
fprintf(f, "|%-12s |%-5c |%-9d |", name.c_str(), area, ch);
as the c_str() function returns the null-terminated array.
In addition, the format strings for the other types also seem incorrect. To print an int, the format specifier is %d, not %c, and the format specify for char is %c, not %d.
Thus the final call to fprintf should be:
fprintf(f, "|%-12s |%-5d |%-9c |", name.c_str(), area, ch);

Char Array with data resetting on operations

I have written a simple function which will take the file name with the extension and return both the extension and the filename minus the extension.
It is working fine but when I was testing it, I see that some where my filename is getting reset. Not always but some times.
#include <stdio.h>
#include <string.h>
#include <string>
#define EXTENSION_STR_MAX (16)
#define METADATA_STR_MAX (129)
struct meta_data_t
{
char filename[METADATA_STR_MAX];
char fileextension[EXTENSION_STR_MAX];
};
void GetFileExtMetadata(const char* fileName, char* fileExt, char* updateFileName)
{
// NULL Checks
if((NULL == fileName) || (NULL == fileExt) || (NULL == updateFileName))
{
printf("NULL :-/ \n");
return;
}
// Find the position of the last dot
char * pch = NULL;
pch = strrchr(fileName, '.');
if((NULL == pch) || (fileName == pch))
{
printf("Nope\n");
}
else
{
// Copy ot the extension
char fileextension[15];
strncpy(fileextension, (pch+1),15);
strcpy(fileExt, ".");
strcat(fileExt, fileextension);
// Remove the extension formthe filename
*pch = '\0';
strncpy(updateFileName, fileName, (METADATA_STR_MAX-1));
updateFileName[METADATA_STR_MAX-1] = 0;
}
}
int main()
{
meta_data_t test1 = {};
meta_data_t test2 = {};
meta_data_t test3 = {};
char tempfilename[METADATA_STR_MAX];
strncpy(test1.filename, "Poker Face.mp3", (METADATA_STR_MAX-1));
test1.filename[METADATA_STR_MAX-1] = 0;
strncpy(test2.filename, "Love.is.in.the.air.wma is the ext", (METADATA_STR_MAX-1));
test2.filename[METADATA_STR_MAX-1] = 0;
strncpy(test3.filename, "Crazy.ThisisatesttoCheckLength", (METADATA_STR_MAX-1));
test3.filename[METADATA_STR_MAX-1] = 0;
printf("%s \n",test1.filename);
printf("%s \n",test2.filename);
printf("%s \n\n",test3.filename);
strncpy(tempfilename, test1.filename, (METADATA_STR_MAX-1));
tempfilename[METADATA_STR_MAX-1] = 0;
GetFileExtMetadata(tempfilename, test1.fileextension, test1.filename);
printf(" BEFORE %s \n",test2.filename);
strncpy(tempfilename, test2.filename, (METADATA_STR_MAX-1));
tempfilename[METADATA_STR_MAX-1] = 0;
GetFileExtMetadata(tempfilename, test2.fileextension, test2.filename);
printf(" AFTER1 %s \n",test2.filename);
strncpy(tempfilename, test3.filename, (METADATA_STR_MAX-1));
tempfilename[METADATA_STR_MAX-1] = 0;
GetFileExtMetadata(tempfilename, test3.fileextension, test3.filename);
printf(" AFTER2 %s \n",test2.filename); // NOT GOOD
printf("%s - %s\n",test1.filename, test1.fileextension);
printf("%s - %s\n",test2.filename, test2.fileextension);
printf("%s - %s\n",test3.filename, test3.fileextension);
printf("%s \n",test1.filename);
printf("%s \n",test2.filename);
printf("%s \n",test3.filename);
return 0;
}
Result:
Poker Face.mp3
Love.is.in.the.air.wma is the ext
Crazy.ThisisatesttoCheckLength
BEFORE Love.is.in.the.air.wma is the ext
AFTER1 Love.is.in.the.air
AFTER2
Poker Face - .mp3
- .wma is the ext
Crazy - .ThisisatesttoCh
Poker Face
Crazy
I see tht the file name Love.is.in.the.air is becoming empty after I run the function for the third time. I am unable to understand why this is happening.
Any clue?
Thanks
Isn't the buffer to hold the file extension too small? It looks like it is 16 chars (EXTENSION_STR_MAX), but "Love.is.in.the.air.wma" is more than that. So you get classical buffer overrun.
Try debugging the code once and you will find your answer.
And reset the contents of "tempfilename" before copying another string into it.
Safe Coding.

sub string in char* in c++ with strtok to the end of the row

I try to cat a string that type in char* in c++
this is my code
void DBManager::printMatched(char* line, char* fileName)
{
line = strtok(line,"Show");
char* teamAName = strtok(line," ");
char* teamACity = strtok(NULL,"-");
char* teamBName = strtok(NULL," ");
char* teamBCity = strtok(NULL,"\n");
}
and this is the text in line
"Show abcde fghij - klmnop qrstu"
this is the variable data:
teamAName = abcde
teamACity = fghij
teamBName = klmnop
teamBCity = qrs
how can i fix teamBCity i need to cut to the in of the row.
i work on Linux system.
I think this is what you want. Not entirely sure given your example. It can obviously be improved upon and maybe you want to use more c++ish facilities?
void DBManager::printMatched(char* line, char* fileName)
{
char* linecpy = strdup(line);
char* dummy = strtok(linecpy," ");
char* teamAName = strtok(NULL," ");
char* teamACity = strtok(NULL," ");
dummy = strtok(NULL," ");
char* teamBName = strtok(NULL," ");
char* teamBCity = strtok(NULL," \n");
printf("teamAName %s\n", teamAName);
printf("teamACity %s\n", teamACity);
printf("teamBName %s\n", teamBName);
printf("teamBCity %s\n", teamBCity);
// do something with strings here?
}

C++, SQLite - pointer to pointer to string

I work with C++ and SQLite3 (with Microsoft Visual C++ 2008) and would like to read a value from my database and store it in a variable to work with it on.
The select statement works fine, but every time I viewed the callback function and try to read the value from char **argv, I get "only" the memory address, or the first ASCII character of the value, which is in the database. What am I doing wrong?
Here is the callback function:
static int callback(void *pArg, int argc, char **argv, char **azColName)
{
fprintf(f, "Callback aufgerufen!\n");
int i;
for(i=0; i<argc; i++)
{
fprintf(f, azColName[i]);
fprintf(f, " = ");
if(argv[i]){
fprintf(f, argv[i]);
//unsigned int x = argv[i];
}
else
fprintf(f, "NULL");
fprintf(f, "\n");
}
fprintf(f, "\n");
return 0;
}
I tried it without the callback function, but again I get the same result and I've tried different ways to store the value in a variable.
while (sqlite3_step(stmt) == SQLITE_ROW)
{
fprintf(f, "%s\n", sqlite3_column_text(stmt, 0));
//const unsigned char *c = sqlite3_column_text(stmt, 0);
fprintf(f, "%u\n", sqlite3_column_int(stmt, 0));
//unsigned int z = *sqlite3_column_int(stmt, 0);
stmt_count++;
}
Is it perhaps not possible to access the value or to store it in a variable?
I don't see why you need a callback - this should work (depending on the size of the data):
char myvalue[100];
while (sqlite3_step(stmt) == SQLITE_ROW)
{
strcpy( myvalue, (const char *) sqlite3_column_text(stmt, 0) );
// do something with myvalue
stmt_count++;
}