从其他指针分配 C 指针内容

  • 本文关键字:指针 分配 其他 pointers
  • 更新时间 :
  • 英文 :


当我试图解决丹尼斯·里奇的问题时。我收到以下错误。但我不知道,为什么会这样。似乎它应该有效。我正在使用MacOS Mojave和标准的gcc编译器。我的源代码如下。

#include <stdio.h>
#include <string.h>
// copies most n characters of t to s; 
char *sstrcnpy(char *s, char *t, int n)
{
    // *pointer - content of the pointer will be assigned 
    char *ret; // ret stores the content of the dst 
    while(n--){
        *ret++ = *t++; 
    }
    printf("%sn", ret);  
    return ret; 
}
int main()
{
    char *s = "Destination"; 
    char *t = "sour"; 
    char *sstrcnpy(char *s, char *t, int n); 
    sstrcnpy(s,t,3);
    printf("%sn", s);
    return 0; 
}

然后当我尝试运行此代码时。终端给了我以下错误。

nasantogtokhs-MacBook-Pro:C nasaa$ ./5_5
Segmentation fault: 11

或者不是分割错误,而是其他一些源代码

bus error: 10 

然后我尝试使用 Mac 的 lldb 向下挖掘。然后我得到了以下错误。

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x0000000100000ef7 5_5`sstrcnpy(s="Destination", t="our", n=2) at exercise_5_5.c:10
   7        // *pointer - content of the pointer will be assigned 
   8        char *ret; // ret stores the content of the dst 
   9        while(n--){
-> 10           *ret++ = *t++; 
   11       }
   12       printf("%sn", ret);  
   13       return ret;

我认为这与内存访问有关。似乎不知何故,我的计算机不允许将值分配给单独函数上的指针内容。但我看到了其他例子。似乎它应该可以正常工作。

谢谢你的时间。

我已经想通了。显然,当我初始化 char 的指针时,它无法更改,但是如果我们为它分配内存,我们可以更改内容。我认为该错误的原因是,当我通过显式分配给 char 数组来初始化它时,程序正在尝试访问不可接受的内存块并尝试更改它,这是正确的,因为初始化只是将内存中常量的地址映射到指针。当使用动态内存分配时,一开始在分配给指针和strcpy函数的内存中没有常量,正在复制字符。

最新更新