简体   繁体   中英

pointer to char array seg fault on strcpy , but work with equal sign

I would like to know why does the pointer of char array can get affected a value with the equals sign as it would normally have to be string copied ? Why can I print the content of anArray[0].ptr[0] as a %s string ?

Is there a way to copy the whole string to the structure in anArray[0] and keeping it even if hello is freed ?

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

struct arrayOf {
  int line;
  int col;
  char ** ptr;
}

int main(void){

 char * hello = "Hello";

 struct arrayOf anArray[5];
 anArray[0].ptr = malloc(sizeof(char*));
 anArray[0].ptr[0] = malloc(100*sizeof(char));

 anArray[0].ptr[0] = hello; //work
 strcpy(anArray[0].ptr[0], hello); //seg fault

return EXIT_SUCCESS;
}

You're overwriting anArray[0].ptr[0] with the assignment (causing a memory leak), so anArray[0].ptr[0] is no longer pointing to the allocated memory.

strcpy(anArray[0].ptr[0], hello); //copied hello to anArray[0].ptr[0]
anArray[0].ptr[0] = hello; //cause a memory leak and anArray[0].ptr[0] points to unwritable memory(probably)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM