-7

i tried coping a string to a pointer using strcpy. it causes a segmentation fault.any reason for that.

#include <stdio.h>
#include <string.h>
int main()
{   
    char *str=NULL;
    strcpy(str,"C-DAC");
    printf("%s\n",str); 
    return 1;
}
  • You’re trying to copy stuff to `NULL`. `NULL` is not a valid place to copy stuff. – Ry- Jun 30 '17 at 06:17
  • Tell me, did you completely ignore `char *str=NULL;`? – Sourav Ghosh Jun 30 '17 at 06:20
  • I can't believe at least 10 questions like this is posted daily. – tilz0R Jun 30 '17 at 06:23
  • change to [`strdup`](http://en.cppreference.com/w/c/experimental/dynamic/strdup) – phuclv Jun 30 '17 at 06:25
  • 3
    @tilz0R I can't believe at least 10 questions like this are _answered_ daily. If you are going to whine about it, then why do you answer such questions and encourage more of the same? There's plenty of canonical duplicates to pick from for closing this. Flag or close vote. – Lundin Jun 30 '17 at 06:27
  • @Lundin I would rather ban those people. – tilz0R Jun 30 '17 at 06:27
  • @tilz0R no one is forcing you to answer. if u dont the question dont answer mind your own business. or is it the case that u like to poke your nose everywhere. – Pranay Saraiwala Jul 06 '17 at 04:47

2 Answers2

0

WHere does your string point to? Nowhere!

That's why you have segmentation fault. You have to either allocate variable on stack as array or define it as pointer and later allocate memory using malloc. When using malloc, don't forget to include "stdlib.h"

Either do this:

char str[6];
strcpy(str,"C-DAC");

or

char *str=malloc(sizeof(*str) * 6);
strcpy(str,"C-DAC");
tilz0R
  • 6,949
  • 2
  • 21
  • 37
0

Computer memory is divided into different segments. A segment for the operating system, for code, for local variables (called a stack), for global variables. Now you are initializing a pointer to NULL which means that the pointer str is now pointing to address 0. That address is simply not available for your program, it's meant for the operating system. In order to protect your system when you try to write that area your program is halted.

MotKohn
  • 3,045
  • 1
  • 23
  • 37