0

when I build this code with codeblock on windows it shows a console windows and stops running, Please help me to fix it

#include <stdio.h>
#include <string.h>

int main ()
{
    char *str="these";
    strupr(str);
    printf("%s", str);
  return 0;
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • `strupr()` is deprecated btw. – Ja͢ck Dec 07 '13 at 01:17
  • You could write your own function that converts a string to upper case; that would be more portable. – Ja͢ck Dec 07 '13 at 01:32
  • 1
    Welcome to Stack Overflow. Please read the [About] page soon. The chances are that the string is stored in read-only memory so any attempt to modify it causes the program to crash. You'd do better with `char str[] = "these";` which will be modifiable data. You should also terminate the output with a newline: `printf("%s\n", str);` though lots of Windows programmers don't bother with such niceties. – Jonathan Leffler Dec 08 '13 at 23:58
  • 1
    Hmmm: the Microsoft page manual page for [`strupr()`](http://msdn.microsoft.com/en-us/library/ms235331.aspx) makes the odd claim that 'These POSIX functions are deprecated', which is funny because [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/toc.htm) doesn't know about the function in the first place. – Jonathan Leffler Dec 09 '13 at 00:02
  • 1
    Not sure what you expect. If the executable were double clicked under Windows, I would expect a console window to open, a string of "THESE" to be printed to the console window and then the console window to close. If you want to keep the console window open then you will need to do some input before the return statement. Also, the strupr() is being done on a constant string and that is not what you should be doing. do `char str[] = "these";` rather than `char *str = "these";` so that you will have a char array rather than pointer to a constant. – Richard Chambers Dec 09 '13 at 00:06

1 Answers1

1

The problem is with your string definition, not with the use of strupr, as some of the comments above already stress it. Your str pointer really points to read-only memory, hence the crash. Look at this question that quotes c-faq.com, or directly in the C standard: "The contents of the arrays are modifiable. On the other hand, the declaration

    char *p = "abc";

defines p with type “pointer to char” and initializes it to point to an object with type “array of char” with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined."

To make that code work simply define an non-const array:

    char str[]="these";
Community
  • 1
  • 1
Liviu
  • 1,859
  • 2
  • 22
  • 48