0

I have a module-level character string declared this way:

char* sStatus = NULL;

This string can be NULL (no status) or have some associated string indicating what the status is. The status string can be read and written from different parts of the program, which is fully synchronous, so there are no concurrency issues.

How can I best update this string? For example, if I write something like:

void addNewRecord(){
   sStatus = "adding new record";
   ...
   ...
   sStatus = "finished adding new record";
}

Then it works, but my fear is that the string is local to the function, so once the function exits the string is no longer valid? The program is not crashing however. I printed out the address of the pointer and it is definitely not on the stack and appears to be in some kind of constant area of memory, so it should be safe.

Nevertheless, I am wondering what the proper way is to handle this kind of data structure usage.

Tyler Durden
  • 11,156
  • 9
  • 64
  • 126

1 Answers1

0

You should use strncpy() to copy the string "adding new record" sStatus:

  memset(sStatus, '\0', strlen(sStatus));  //clear before update
  strncpy(sStatus, "adding new record", strlen((const char *)"adding new record"));

Of course, sStatus should be allocated memory before copying string to it.

Kaizhe Huang
  • 990
  • 5
  • 11
  • In this code "adding new record" is a constant string, no different than mine. How is copying the constant string to an allocated area of memory (the heap presumably) an improvement on simply pointing the status reference to the constant memory string directly? – Tyler Durden Oct 15 '14 at 18:33
  • @TylerDurden, the string "adding new record" acts as a local variable which only exists in the function addNewRecord. After the function is called, this local variable is released. That's why even though your sStatus still point to the same stack address, but different content inside. – Kaizhe Huang Oct 15 '14 at 18:37
  • @TylerDurden , one other way is that, if the status are fixed, let's say only two or three status available. Then you can declare them globally as sStatus. Then you will get what you want. – Kaizhe Huang Oct 15 '14 at 18:38
  • As I said in my post, I printed the pointer to the string literal and it was not on the stack. The pointer appears to be in global constant memory. – Tyler Durden Oct 15 '14 at 18:39
  • Firstly there is no bound checking, you may very well `strcpy()` past the allocated memory. Secondly, yo don't need to `memset()` when `strcpy()` will inject null terminatior anyway. Why waste CPU cycles? – GreenScape Oct 15 '14 at 19:06