【问题标题】:segmentation fault while calling a self-made C function [closed]调用自制C函数时出现分段错误[关闭]
【发布时间】:2018-11-29 06:40:31
【问题描述】:
#include <string.h>
#include <time.h>
#include <stdio.h>

static char* extensionSearch(char * fileName){
    const char* extensions[] = {".exe", ".doc", ".xls", ".ppt", ".txt", ".jpg", ".eml", ".log"};

    char * fName = fileName;
    char* tmpRetValue = "";
    char* finalRetValue = "noExt";
    for(int i=0; i<sizeof(extensions)/sizeof(const char *); i ++)
    {
        tmpRetValue = strstr(fName, extensions[i]);
        if(strcmp(tmpRetValue, extensions[i]) == 0)
        {
            finalRetValue = extensions[i];
        }


    }
    return finalRetValue;
}

int main () {
    char* fileExt = extensionSearch("great.exe");
}

这是一个自制的C函数。我叫它

它会导致分段错误。 发生段错误的原因是 strstr() 返回 NULL,但是当我阅读文档“https://www.tutorialspoint.com/c_standard_library/c_function_strstr.htm”时,它从不返回 NULL。为什么返回NULL?

函数获取一个文件名并检查它是否在函数中具有这些扩展名之一。如果有,则返回文件扩展名。

【问题讨论】:

  • 在哪一行? (是的,你应该自己找出来。)
  • 错误是什么,发生在哪里?
  • printf("%s\n", *fileName); 已经错误,*fileName 返回 char,但 %s 期望 char*
  • 正如@UnholySheep 所说。改为printf("%s\n", fileName)
  • 此外,tutorialspoint 不是 文档。我不会考虑将它用作 a 文档。

标签: c function parameters segmentation-fault


【解决方案1】:

问题很可能在这里:

printf("%s\n", *fileName);

变量fileName 是一个指向char 的指针。只是使用"%s" 格式打印字符串时所期望的类型。但是,取消引用指针会导致将字符串中的第一个字符传递给"%s" 格式。表达式*fileNamefileName[0] 相同。它是一个 char 元素。

格式说明符和参数不匹配会导致undefined behavior,这是导致像您这样的崩溃的常见原因。

【讨论】:

  • 我删除了那行..谢谢你指出来
【解决方案2】:

您必须检查您的strstr 调用的返回值。如果 strstr 返回 NULL,则不能将其传递给 strcmp。你需要做例如

tmpRetValue = strstr(fName, extensions[i]);
if(tmpRetValue != NULL && strcmp(tmpRetValue, extensions[i]) == 0)
{
       finalRetValue = extensions[i];
}

【讨论】:

  • 为什么返回NULL?根据文档,它永远不会返回 NULL。阅读tutorialspoint.com/c_standard_library/c_function_strstr.htm
  • @InchanHwang 在链接的“返回值”一章中,它就在那里说:“如果序列不存在于 haystack 中,则为空指针。”例如,如果您调用 strstr("Essay.doc", ".exe") ,则 strstr 返回一个 NULL 指针,因为在“Essay.doc”字符串中找不到“.exe”。
  • 谢谢!英语不是我的第一语言。我有时会省略细节。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
  • 1970-01-01
  • 2022-01-04
相关资源
最近更新 更多