[英]char pointers in c causing segmentation fault
我對C很陌生,所以也許有人可以闡明為什么我在此程序中遇到分段錯誤:
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *username = "hello";
char *other;
*other = *username;
return 0;
}
為什么此段出錯?
other
尚未初始化。 它指向內存中的某個隨機點,並且您在其中粘貼了一個字符。
您可能要為other
分配一些空間:
char *other = malloc(6); // or 1, or however much space you'll eventually need
*other = *username;
// first char at `other` is now 'h'; the rest is unknown. To make it valid string,
// add a trailing '\0'
other[1] = '\0';
或者,如果您要創建重復的字符串:
char *other = strdup(username);
或者,如果您試圖將other
指向username
位置指向同一位置:
char *other = username;
"Okay as I understand it char *username = "hello";
automatically allocates a place for the string."
更好地定義單詞“ it”(在以上句子中使用)可能會有所幫助; 這就是“編譯器”(不必對鏈接器和加載器有太多的思考)。 the program is executed. 這意味着編譯器執行程序為靜態字符串“ hello”准備了一個位置。 例如,您可以“ grep”可執行文件並發現該可執行文件包含字符串“ hello”。
by the OS, a 'heap' is established where the program may allocate memory dynamically. 操作系統 ,會在程序可以動態分配內存的地方建立一個“堆”。
靜態字符串“ hello”不屬於堆; 並且在運行時未動態“分配”。 相反,它是在編譯時靜態“分配”的。
靜態值(例如字符串“ hello”)無法通過“ realloc()”調整大小,也無法通過“ free()”釋放,因為這些函數僅適用於從“堆”分配的項目,而不適用於靜態“編譯時” ”分配。
以下代碼聲明了靜態字符串“ hello”。 它還聲明了字符指針“用戶名”,並初始化了指針以指向靜態字符串。
char *username = "hello";
以下代碼聲明了一個字符指針“ other”,並將其保留為未初始化狀態。 作為“其他”的對象尚未初始化,並且指針始終指向某處。 未初始化的“其他”指針可能指向隨機內存位置(實際上不存在)。
char *other;
character ('h') from where username is pointing, to where 'other' is pointing (a random memory location which does not actually exist). 下面的行嘗試將字符('h')從用戶名指向的位置復制到'其他'指向的位置(實際上不存在的隨機內存位置)。
*other = *username;
這就是產生“分段故障”的原因。
僅供參考,以下語句會使指針“用戶名”和“其他”指向同一位置,即靜態字符串“ hello”:
char *other;
other = username;
...與以下內容相同:
char *other = username;
如果願意,可以使“ hello”從堆中分配(在運行時),如下所示:
char *username = strdup("hello");
如果您想要“其他”中的另一個副本:
char *other = strdup("hello");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.