【问题标题】:pointer to char array seg fault on strcpy , but work with equal sign指向 strcpy 上的 char 数组段错误的指针,但使用等号
【发布时间】:2013-11-24 01:47:50
【问题描述】:

我想知道为什么 char 数组的指针会影响带有等号的值,因为它通常必须被字符串复制?为什么我可以将 anArray[0].ptr[0] 的内容打印为 %s 字符串?

有没有办法将整个字符串复制到 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;
}

【问题讨论】:

    标签: c char segmentation-fault


    【解决方案1】:

    您正在用赋值覆盖 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)
    

    【讨论】:

    • 实际上,equals 不会产生 seg 错误,而 strcpy 会。
    • anArray[0].ptr[0] 指向的相等变化,因此当您尝试在其上使用 strcpy 时,您会得到段错误
    • 即使删除了等于的表达式也会崩溃。只留下你看到的 strcpy
    猜你喜欢
    • 1970-01-01
    • 2013-03-31
    • 2021-08-11
    • 1970-01-01
    • 2018-04-05
    • 2015-09-10
    • 2021-01-26
    • 2016-01-27
    • 2012-03-19
    相关资源
    最近更新 更多