C:从函数返回 char* 会导致 printf 崩溃

标签 c pointers return printf segmentation-fault

这里是包含 printf 的代码(带有行号,来自 think.c):

30: char *think = getRandomMemory();
31: printf("\33[2K\r");
32: if(think == NULL)
33:     think = "NULL";
34: printf("I have an idea: %s\n", think);
35: parse(think);
36: freeMemory(think);
37: printf("> ");

来自 getRandomMemory() 的代码确保返回的指针指向堆分配的空间:

char *getRandomMemory()
{
    char *ret;

    // --SNIP--

    size_t l = strlen(ret) + 1;
    char *rret = getMemory(sizeof(char) * l);
    for(int i = 0; i < l; i++)
        rret[i] = ret[i];
    printf("--- %s ---\n", rret);
    return rret;
}

最后,这就是 gdb 运行时给我的信息。请注意,“--- test ---”来自上面的“printf("--- %s ---\n", rret)”:

(gdb) run
Starting program: /home/v10lator/Private/projekte/KI/Lizzy 
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".
Loading Lizzy 0.1... Done!

> --- test ---
[New Thread 0x7ffff781f700 (LWP 32359)]

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff781f700 (LWP 32359)]
0x00007ffff7869490 in _IO_vfprintf_internal (s=<optimized out>, format=<optimized out>, 
ap=ap@entry=0x7ffff781ee68) at vfprintf.c:1642
1642    vfprintf.c: Datei oder Verzeichnis nicht gefunden.
(gdb) bt
#0  0x00007ffff7869490 in _IO_vfprintf_internal (s=<optimized out>, format=<optimized out>, 
ap=ap@entry=0x7ffff781ee68) at vfprintf.c:1642
#1  0x00007ffff7919235 in ___printf_chk (flag=1, format=<optimized out>) at printf_chk.c:35
#2  0x00000000004016bc in printf () at /usr/include/bits/stdio2.h:104
#3  run (first=<optimized out>) at think.c:34
#4  0x00007ffff7bc64c6 in start_thread (arg=0x7ffff781f700) at pthread_create.c:333
#5  0x00007ffff790a86d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109

我真的不知道这里出了什么问题,所以希望有人能看到这个错误。

//编辑:忘记了 getMemory/freeMemory 函数:

/*
  * This allocates memory.
  * The difference between usig malloc directly is that this function will
  * print an error and exit the program in case something bad happens.
  */
char *getMemory(size_t size)
{
    char *mem = malloc(size);
    if(mem == NULL)
        crashWithMsg("Internal error (malloc failed)!");
    return mem;
}

/*
 * This deallocates memory.
 * The difference between using free directly is that this function will
 * set the pointer to NULL afterwards.
 */
void freeMemory(void **ptr)
{
    free(*ptr);
    *ptr = NULL;
}

最佳答案

问题在于您对 freeMemory 的调用:

freeMemory(think);

您已经对该函数进行了编码,以获取要释放的内存的指针地址,而不是指针本身。所以你需要这样调用它:

freeMemory(&think);

关于C:从函数返回 char* 会导致 printf 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34312063/

相关文章:

c - 将套接字绑定(bind)到网络接口(interface)时出错

C中的契约(Contract)设计模式

将字符复制到字符*

使用 strcmp/strncmp 比较 int8_t 和 char*

macos - 为什么我的 x86 链表函数会抛出段错误?

检查不存在的文件是否可执行 -Win32 C

c - 用户输入.txt文件搜索C

c++ - 如何使用指针到指针来传递矩阵?

c - 具有多个参数的返回语句

ruby - Ruby 中的隐式返回值