-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;
}

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");
unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
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,485
  • 1
  • 24
  • 41