繁体   English   中英

总线:C 中的错误 10 是什么意思

[英]What is the meaning of Bus: error 10 in C

下面是我的代码

#import <stdio.h>
#import <string.h>

int main(int argc, const char *argv[])
{
    char *str = "First string";
    char *str2 = "Second string";
    
    strcpy(str, str2);
    return 0;
}

它编译得很好,没有任何警告或错误,但是当我运行代码时,出现以下错误

Bus error: 10

我错过了什么 ?

一方面,您不能修改字符串文字。 这是未定义的行为。

要解决此问题,您可以将str本地数组:

char str[] = "First string";

现在,您将遇到第二个问题,即str不足以容纳str2 所以你需要增加它的长度。 否则,您将超出str - 这也是未定义的行为。

要解决第二个问题,您要么需要使str至少与str2一样长。 或者动态分配:

char *str2 = "Second string";
char *str = malloc(strlen(str2) + 1);  //  Allocate memory
//  Maybe check for NULL.

strcpy(str, str2);

//  Always remember to free it.
free(str);

还有其他更优雅的方法可以做到这一点,包括 VLA(在 C99 中)和堆栈分配,但我不会深入研究它们,因为它们的使用有些问题。


正如@SangeethSaravanaraj 在评论中指出的那样,每个人都错过了#import 它应该是#include

#include <stdio.h>
#include <string.h>

没有为字符串分配空间。 将数组(或)指针与malloc()free()

除此之外

#import <stdio.h>
#import <string.h>

应该

#include <stdio.h>
#include <string.h>

笔记:

  • 任何malloc() ed 必须是free() ed
  • 您需要为长度为n的字符串分配n + 1个字节(最后一个字节用于\\0

请您将以下代码作为参考

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

int main(int argc, char *argv[])
{
    //char *str1 = "First string";
    char *str1 = "First string is a big string";
    char *str2 = NULL;

    if ((str2 = (char *) malloc(sizeof(char) * strlen(str1) + 1)) == NULL) {
        printf("unable to allocate memory \n");
        return -1; 
    }   

    strcpy(str2, str1);

    printf("str1 : %s \n", str1);
    printf("str2 : %s \n", str2);

    free(str2);
    return 0;
}

str2指向一个静态分配的常量字符数组。 你不能写它/覆盖它。 您需要通过*alloc系列函数动态分配空间。

字符串文字在 C 中是不可修改的

您的代码尝试覆盖字符串文字。 这是未定义的行为。

有几种方法可以解决这个问题:

  1. 使用malloc()然后strcpy()然后free()
  2. str转换为数组并使用strcpy()
  3. 使用strdup()

这是因为 str 指向一个字符串文字意味着一个常量字符串......但你正试图通过复制来修改它。 注意:如果由于内存分配而出现错误,它会在运行时出现分段错误。但此错误是由于常量字符串修改而出现的,或者您可以通过以下了解更多详细信息 abt bus error :

现在 x86 上的总线错误很少见,并且在您的处理器甚至无法尝试请求的内存访问时发生,通常:

  • 使用地址不满足对齐要求的处理器指令。

访问不属于您的进程的内存时会发生分段错误,它们很常见,通常是由以下原因造成的:

  • 使用指向已释放内容的指针。
  • 使用未初始化的虚假指针。
  • 使用空指针。
  • 溢出缓冲区。

更准确地说,这不是操纵会导致问题的指针本身,而是访问它指向的内存(取消引用)。

每当您使用指针变量(星号)时,例如

char *str = "First string";

你需要为它分配内存

str = malloc(strlen(*str))

让我解释一下为什么会出现此错误“总线错误:10”

char *str1 = "First string";
// for this statement the memory will be allocated into the CODE/TEXT segment which is READ-ONLY

char *str2 = "Second string";
// for this statement the memory will be allocated into the CODE/TEXT segment which is READ-ONLY

strcpy(str1, str2);
// This function will copy the content from str2 into str1, this is not possible because you are try to perform READ WRITE operation inside the READ-ONLY segment.Which was the root cause 

如果要执行字符串操作,请使用自动变量(STACK 段)或动态变量(HEAP 段)

瓦桑特

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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