0

The following program is showing unexpected result

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* num1;
    num1 = malloc(100*sizeof(char));
    num1 = "38462879";
    printf("%s\n",num1);
    num1[0]='5';
    printf("%s\n",num1);
    return 0;
}

I expect it to print the given string and then print the given string with the first letter replaced by 5 instead of 3 in the next line.

But it is printing the given string in first line and then the program is not going ahead.

Can you please help??

2
  • 1
    Changing code after commands or answers were given should be avoided. Commented Mar 30, 2020 at 7:48
  • 2
    You first allocate dynamic memory. Then you throw away that address and replace it with the address of an immutable string literal. That is a memory leak Commented Mar 30, 2020 at 7:49

3 Answers 3

1

By saying

 num1 = "38462879";

you're essentially

  • Overwriting the allocated pointer to the memory (memory leak)
  • Making num1 point to a string literal. (illegal to attempt to modify the content)

Later your attempt to modify a part of that literal will invoke undefined behavior. What you need instead is to use strcpy(), like

 strcpy (num1, "38462879");

That said, couple of general suggestion:

  • for a hosted environment, int main() should at least be int main(void).
  • You must always check for the success of a function call (esp. library functions) before using the returned value.
  • in C, sizeof(char) is defined to be 1, it's a redundant multiplier.
Sign up to request clarification or add additional context in comments.

2 Comments

What is the problem in making num1 point to a string literal? And why modifying a part of that literal is invoking undefined behaviour??
@Martund Because the C standard says so. I will add the relevant quotes, see if that helps.
0

Do not assign a constant string to num1, but use strcpy(): strcpy(num1, "whatever");

2 Comments

You can assign constant strings to char *. But you are right, because later num1[0] is modified.
Do not assign a constant string to num1 why not? Some explanation needed.
0

this is a character ,you can't allocate memory for one character and store a string it it , it only has space for one character . I think you meant char *num1.

2 Comments

@SouravGhosh it was char num1 before edit. not char* num1
Now once it has been changed, this answer also should change, is not it?

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.