函数返回错误值是标记返回值是" char *"

时间:2015-11-15 10:18:40

标签: c

这是我的代码,当我返回" fo"时,结果是" 0x7fffffffd870" fo" ",我的问题是如何让它回归" fo"?

#include <stdio.h>
#include <string.h>
#include <regex.h>

char *substr(char *s, int from, int to) {
    int n = to - from + 1;
    char subs[n];
    strncpy(subs, s + from, n);
    return subs;
}

int main(int argc, char **argv) {
    char *s = substr("foo", 0, 1);
    puts(s);
    return (0);
};

更新,这是正确的代码,但我不知道char subs[n]char* subs=malloc(n)

之间的差异
char *substr(char *s, int from, int to) {
    int n = to - from + 1;
    char *subs = malloc(n);
    strncpy(subs, s + from, n);
    return subs;
}

int main(int argc, char **argv) {
    char *s = substr("foo", 0, 1);
    puts(s);
    return (0);
};

1 个答案:

答案 0 :(得分:0)

当每个程序开始执行时,它会在堆栈上分配内存。

在第一个程序中,subs char数组是自动变量,内存在堆栈上分配。 一旦函数调用完成,它将删除其堆栈内存。 在函数调用的最后,你返回数组的地址,在函数调用结束后该地址有垃圾值,导致悬空指针(即你试图访问没有任何内容的内存)。 / p>

为了解决这种情况,您需要分配堆内存,这可以使用 c 中的 malloc 来完成。一旦它在堆上创建了内存,程序就不会自动删除它,你需要使用 free 关键字删除它,否则会导致溢出。 解决这个问题的另一种方法是,创建全局变量,其范围是整个程序,您可以随意访问它。

相关问题