0

I am working on Legacy code where a string literal is assigned to a variable of type PTCHAR (pointer to char) which is defined in the header: typedef WCHAR TCHAR, *PTCHAR;

PTCHAR str;
str = _tcsrchr(dir, '\\');
*(str++)=0;

str = TEXT("This is stackoverflow");

I am getting a warning 'conversion from a string literal to pointer-to-character (non-const) is deprecated', I understand warning is coming because a const is assigned to a non-const pointer variable, but I can't make str CONST(LPCSTR) because it is being modified in code as *(str++)=0;

Is there a way to solve this?

User1714
  • 37
  • 1
  • 6
  • There is a difference between a non-const pointer to const and a const pointer to non-const. Are you aware of that? – Yunnosch Jun 11 '20 at 07:54
  • Use `LPCTSTR` in-place of `PTCHAR` see: https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types – Richard Critten Jun 11 '20 at 08:15
  • I did the same thing, but then *(str++)=0 will throw an error. – User1714 Jun 11 '20 at 08:27
  • 1
    The string `"This is stackoverflow"` is const (probably in read-only memory). Any attempt to modify it is Undefined Behaviour. Using `LPCTSTR` will give you compilation errors instead of UB. – Richard Critten Jun 11 '20 at 08:46
  • Please make a [mcve], especially of the part with the `*(str++)=0;`. The problem might be there. Maybe in the shape of a https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – Yunnosch Jun 11 '20 at 08:57
  • updated the required code – User1714 Jun 11 '20 at 10:12
  • @RichardCritten a string literal is unlikely to be in read-only memory in a modern system. That doesn't make it any less UB, but does lessen the chances that you'll notice. – Mark Ransom Jun 11 '20 at 20:24
  • @MarkRansom I didn't know that; I though the loader could mark pages as read only and that's where string literals (and other constant data) would be loaded. – Richard Critten Jun 11 '20 at 21:05
  • any suggestions on this?? :| how to solve this issue – User1714 Jun 13 '20 at 13:55

1 Answers1

2

If you want to modify the string later, you will need to make a copy of it, for example using _wcsdup(). Don't forget to free() it when done.

Brecht Sanders
  • 6,215
  • 1
  • 16
  • 40
  • @Yunnosch Why do you think string is not modified? `*(str++)=0;` is string a modification. – Codo Jun 11 '20 at 08:18
  • @Codo You are right. I was over-focussing on the `str++` NOT changing it. Sorry. (By the way; good style asking "why" instead of saying "wrong", though I was.) – Yunnosch Jun 11 '20 at 08:55