【问题标题】:Converting char * to uppercase segfaults将 char * 转换为大写的段错误
【发布时间】:2016-02-04 19:43:49
【问题描述】:

我有一个简单的程序,其中有一个我在外部编写的字符串(在这个片段的情况下,它是用户创建的)。我正在尝试将其中的某些部分大写。

我首先用分隔符将其分隔,并尝试使用 toupper 函数将其大写,但是我似乎遇到了段错误。运行 valgrind 不会出现任何错误,只是简单地说:

Process terminating with default action of signal 11 (SIGSEGV)
==10180==  Bad permissions for mapped region at address 0x4007B9

代码:

int main(void) {
    char * test;

    char * f;
    char * s;
    char * p;

    test = "first:second:third:fourth:";
    f = strtok(test,":");


    for(p = f; *p; *p = toupper(*p), p++); //segfaults

    printf("f is %s \n",f); //this should print "FIRST" as it should be capitalized

    return 0;
}

【问题讨论】:

  • f = s = p = test = malloc(sizeof(char * ) * 10); 这是什么?
  • 内存泄漏,内存大小不正确...太多...
  • @SouravGhosh 哇!我没看到啊!!!!当我看到test = strtok(STRING_LITERAL, ...) 时,我立即回答。
  • 我认为 mallocing char * 是个好习惯?
  • 你可能需要先读一本好书,不要冒犯。

标签: c string pointers segmentation-fault


【解决方案1】:

你不能在字符串文字上使用strtok(),因为它修改了它的参数,你不能修改字符串文字。

你也不能在这个循环中修改它

for (p = f; *p; *p = toupper(*p), p++); //segfaults

您需要一个数组或动态分配的内存块,两者都是可写的,您可以使用这样的字符串字面量来初始化数组

char array[] = "This is a string literal, you are not allowed to modify it";
/* Now the arest of the code could work but ... */

您还需要检查strtok() 的返回值,即NULL,当它没有找到您要查找的内容时。

使用malloc() 你也可以这样做

cosnt char *string_literal = "This is a sample string";
size_t length = strlen(string_literal);
char *buffer = malloc(length + 1);
if (buffer == NULL)
    return -1; // Allocation failure.
memcpy(buffer, string_literal, length + 1);
//                                      ^ copy the null terminator too
// Process your newly allocated copy here and,
free(buffer);

注意:关于您的原始代码与

f = s = p = test = malloc(sizeof(char * ) * 10);

malloc() 不用作一般的初始化函数,它用于获取指向您可以在程序中使用的内存的指针,您可以对其进行读/写。当您使用 malloc() 请求内存时,您会请求在程序中使用特定(通常是准确)字节数。

如果返回的指针不是NULL,则返回的指针可用,如果出现错误或系统内存不足,它将返回NULL

您的代码有一个主要问题,因为所有指针 fsptest 都指向相同的内存地址,并且还因为您分配了一个任意大小,它可能是也可能不是您的想要/需要。

当你free(f) 然后继续free(s) 时,你释放了同一个指针两次,实际上你做的不止这些。在同一个指针上调用free() 两次会调用未定义的行为。

【讨论】:

  • 喂!你的代表通过了我! ;-)
猜你喜欢
  • 2011-02-23
  • 1970-01-01
  • 2016-05-12
  • 2021-10-16
  • 1970-01-01
  • 2018-10-20
  • 2022-01-22
  • 2021-11-09
  • 2015-07-14
相关资源
最近更新 更多