簡體   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