[英]Seg fault when reading a line into dynamically allocated char pointer array
[英]pointer to char array seg fault on strcpy , but work with equal sign
我想知道为什么char数组的指针为什么会受到带有等号的值的影响,因为通常必须将其复制为字符串? 为什么我要以%s字符串形式打印anArray [0] .ptr [0]的内容?
有没有一种方法可以将整个字符串复制到anArray [0]中的结构中,甚至在释放hello时也可以保留它?
#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;
}
您正在使用分配覆盖anArray [0] .ptr [0](导致内存泄漏),因此anArray [0] .ptr [0]不再指向分配的内存。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.