錯誤的權限我有練習5-13 K & R的問題,練習的目標是製作一個與* nix命令相同的函數尾部,這裏是我的功能:strcpy()錯誤:映射區域在地址
#include <stdio.h>
#include <string.h>
#include "tail.h"
int tail(int n)
{
char *saved_lines[n];
for (int i = 0; i < n; i++)
saved_lines[i] = "\0";
int line_state[n];
for (int j = 0; j < n; j++)
line_state[j] = 0;
int num_lines = 0, i = 0;
char line[MAXLINE];
saved_lines[n - 1] = "\0";
while (get_line(line, MAXLINE) > 0)
{
for (i = 0; i < n - 1; i++)
{
strcpy(saved_lines[i], saved_lines[i + 1]);
line_state[i] = line_state[i + 1];
}
strcpy(saved_lines[n - 1], line);
line_state[n - 1] = 1;
}
printf("last %d lines: \n", n);
for (i = 0; i < n; i++)
if (line_state[i] == 1)
printf("%d: %s\n", i, saved_lines[i]);
}
問題是,當我運行它,我得到一個Segmentation fault (core dumped)
錯誤,並通過Valgrind的運行它顯示的錯誤來自調用strcpy
:
==25284== Process terminating with default action of signal 11 (SIGSEGV): dumping core
==25284== Bad permissions for mapped region at address 0x108E64
...我不不明白爲什麼,起初strcpy
與01有問題個指針被初始化非,固定與
for(int i=0;i<n;i++)
saved_lines[i]="\0";
沒有幫助...任何想法可能導致此?提前致謝!
編輯:開始 - >初始化
指針都被初始化爲指向字符串文字。你需要一些實際的存儲空間。 –
OT:「*啓動*」--->「初始化」 – alk
爲char數組中的每個單詞分配一些內存,它們指向字符串文字。字符文字作爲二進制文件的一部分存儲在「只讀」位置。你應該知道'strcpy'修改了它的參數。這將幫助你,[關於字符串文字](https://stackoverflow.com/questions/2589949/string-literals-where-do-they-go),[SimilarQuestion](https://stackoverflow.com/questions/ 11379412/crash-when-handling-char-initd-with-string-literal-but-with-malloc) – WhiteSword