2

I'm trying to make a simple code in c language (Stupid question, but I'm learning), I dont understand that this code gives me an error ... I must be doing wrong, I can not know that I have to change...sorry for my English ... thanks in advance to all

#include <stdio.h>
#include <ctype.h>

char* to_up(char* str_); 

int main()
{
    char any_phrase[] = "This is a phrase";
    printf("%s\n", to_up(any_phrase));
    printf("%s\n", to_up("this is another phrase"));
    return 0;
}

char* to_up(char* str_) 
{
    int i;
    for (i=0; str_[i]; i++) 
        str_[i] = toupper(str_[i]);
    return str_;
}
1
  • toupper() needs to be passed an unsigned char (implicitly converted to int) or EOF. You should write it like toupper((unsigned char)str_[i]). Problem can show up if you get a phrase like "¿Cómo te llamas?". Commented Sep 19, 2010 at 17:25

4 Answers 4

3

The reason for the error is that when you pass the string as "this is another phrase" on its own, as in not contained in a variable, the string is what's known as a string literal. What this means, among other things, is that the string is constant: you simply are not allowed to modify.

To solve your problem you'd have to store the string in a variable so it is allowed to be modified by your to_up() function call since it modifies the contents of the string.

Sign up to request clarification or add additional context in comments.

Comments

2

A string literal is usually in read-only memory. As far as the standard is concerned, trying to modify it will result in undefined behaviour regardless of where it is in memory. There have been many questions asked about this problem already.

Comments

1

In this call

printf("%s\n", to_up("this is another phrase"));

You are trying to modify a string literal.

Comments

1

The code compiles OK for me, but gives a bus error (core dump) at runtime.

The trouble is that a string literal can be stored in read-only memory, so you can't modify the literal string as your code does. With enough compiler warnings enabled, your compiler will warn you (GCC requires -Wwrite-strings - at least, in GCC 4.4 and above).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.