![](/img/trans.png)
[英]Why am I getting Segmentation fault (core dumped) or bus error (core dumped) when trying to populate a struct?
[英]getting error Segmentation fault (core dumped) when trying to pass a string to a function
當我嘗試將當前時間作為字符串傳遞給我的代碼中的函數記錄器時,我得到一個錯誤,說“分段錯誤(核心轉儲)”。 但是當我把static char str[30]
放入錯誤時。 但沒有錯誤,生成的文件無法打開它。
void logger(char * logType, int loggingLevel, char * massage)
{
FILE *fp = fopen("log.txt", "a");
fprintf(fp, "%s|%d|%s|%s",logType,loggingLevel,massage,currentTime());
fclose(fp);
}
char * currentTime(void)
{
time_t rawtime;
char str[30];
char *string;
struct tm * timeInfo;
time(&rawtime);
timeInfo = localtime(&rawtime);
strftime(str, 26, "%Y:%m:%d %H:%M:%S", timeInfo);
return str;
}
所以我以前做過currentTime函數
char * currentTime(void) {
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
return asctime(timeinfo);
}
它工作正常,但這不是我需要顯示時間的方式。
您正在從函數currentTime()
返回一個局部變量,該變量是未定義的行為 。
將函數簽名更改為: char * currentTime(char *inputBuffer, size_t bufLen)
您正在從currentTime
函數返回指向局部變量(此處為str
緩沖區)的指針。
你不能這樣做,因為一旦局部變量超出范圍(即你離開currentTime
函數),它們的內容是未定義的,它們大多數時候都會包含垃圾。
因此,您必須將str
聲明為static:
static char str[30];
在這種情況下, str
在程序執行期間始終存在,而不僅僅是在執行currentTime
函數期間。
但這可能會導致其他問題。
例:
char *time1;
char *time2;
time1 = currentTime();
...
/* somewhat later */
time2 = currentTime();
/* now time1 and time2 point to the same memory location */
/* which contains the current time at the second call */
或者使用線程時的問題。
由於在其他答案中暴露的原因,您的功能不是可重入的,這意味着每次調用它時結果都會被覆蓋。 要為每個調用創建一個專用實例,您還可以使用strdup()
創建一個字符串的副本,可以在使用后使用free()
刪除:
void logger(char * logType, int loggingLevel, char * massage)
{
FILE *fp = fopen("log.txt", "a");
char *sTime = currentTime(); //Get the value
fprintf(fp, "%s|%d|%s|%s",logType,loggingLevel,massage, sTime);
free(sTime); //Release the string if no more needed.
fclose(fp);
}
char * currentTime(void)
{
time_t rawtime;
char str[30];
struct tm * timeInfo;
time(&rawtime);
timeInfo = localtime(&rawtime);
strftime(str, 26, "%Y:%m:%d %H:%M:%S", timeInfo);
return strdup(str);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.