Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *str;
    strcpy(str,"Hello");
    printf("%s",str);
    return 0;
}


What I have tried:

I tried with the help of debugger, it shows Segmentation fault in Codeblocks IDE.
Program received signal SIGSEGV, Segmentation fault.
Posted
Updated 16-Apr-16 3:31am
v2

This is because str is just an unitialised pointer to a string. There is no memory allocated where the content of the entered string can be stored and the pointer itself can point to anywhere.

So you must allocate some memory and assign that to the pointer:
C++
// It is always a good idea to initialise variables
char *str = NULL;
char *heapMemory = NULL;
char stackMemory[128];

str = stackMemory;
strcpy(str,"Hello stack");
printf("%s",str);

heapMemory = (char*)malloc(128);
str = heapMemory;
strcpy(str,"Hello heap");
printf("%s",str);
// Heap memory should be freed when not used anymore
free(heapMemory);
 
Share this answer
 
Simple:
C++
char * str;

str is a char * - a pointer to a character. But you don't assign anything to the variable before you try to copy into the memory:
C++
strcpy(str,"Hello");
Which means that the copy operation goes to a nonexistant area of memory, and you get an error.
Assign an area of memory (with malloc perhaps) and it should start to work.

[edit]I HATE MARKDOWN![/edit]
 
Share this answer
 
v2
Quote:
Why this is segmentation fault ?
By your program is done wrong.
The C language is not managed, you have to manually manage memory, and you fail to do it in your program.
C++
strcpy(str,"Hello");

Copies "Hello" to a place you don't own, that is the reason of the segment fault.

You need to learn properly the C language and follow tutos. Knowing the syntax is not enough, there is much more to know.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900