c - 是什么改变了我的 C 字符串中的 char 值?

标签 c string malloc

我的代码中的某些内容正在神秘地替换所有 char在我的const char *里面(upper 内的字符串 foo_add() )带有垃圾值。这似乎发生在调用malloc之后。在foo_add() 。我在函数内部的 Xcode 中设置了断点,并且 uppermalloc 之前就可以了调用,但在后面填充随机值。我是一个完全的 C 新手,所以完全有可能我正在做的事情会产生一些我不知道的副作用。不知道和malloc有没有关系或者不是,我不明白为什么会这样。代码如下。我添加了评论以显示问题发生的位置。

//in Foo.h
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>

typedef struct Foo {
    struct Foo * members[26] ;
} Foo ;

const char * toUpper(const char * in) ;
const char * getSubstring(const char * str, size_t startingIndex) ;

void foo_init(Foo * f) ;
void foo_add(Foo * f, const char * str) ;

//in Foo.c
#include "Foo.h"

const char * toUpper(const char * in) {

    size_t length = strlen(in) ;
    char temp[length + 1] ;

    for (size_t i = 0 ; i < length; i++) {
        temp[i] = toupper(in[i]) ;
    }
    temp[length] = '\0' ;
    char * out = temp ;
    return out ;
}

const char * getSubstring(const char * str, size_t startingIndex) {
    size_t size = (unsigned)(strlen(str) - startingIndex) ;
    char temp[size + 1] ; //+1 for '\0' (terminating char)
    for (size_t i = 0 ; i < size ; i++) {
        temp[i] = str[i + startingIndex] ;
    }
    temp[size] = '\0' ;
    const char * ret = temp ;
    return ret ;
}

void foo_init(Foo * f) {
    for (size_t i = 0 ; i < 26 ; i++) {
        f->members[i] = NULL ;
    }
}

void foo_add(Foo * f, const char * str) {

    const char * upper = toUpper(str) ;
    int index = ((int)upper[0]) - 65 ;

    size_t length = strlen(str) ;
    if (length > 0) {
        if (f->members[index] == NULL) {
            /* debugger says upper = "ABCXYZ" here, which is expected */
            f->members[index] = (Foo *)malloc(sizeof(Foo)) ;
            /* set another debugger breakpoint here - upper is now filled with garbage values */
        }

        /* take substr and call recursively until length == 0 */
        const char * next = getSubstring(upper, 1) ;
        foo_add(f->members[index], next) ;
    }
}

//in main.c
#include <stdio.h>

#include "Foo.h"

int main(int argc, const char * argv[])
{
    Foo f ;
    foo_init(&f) ;

    const char * str = "abcxyz" ;

    foo_add(&f, str) ;
    return 0;
}

最佳答案

罪魁祸首是这段代码:

const char * function(const char * in) {
  char temp[..];
  char *out = temp;
  return out;
}

这里,temp 是在堆栈上分配的,而不是在堆上。这意味着当函数的作用域退出时,它的生命周期就结束了。您应该使用例如 char *temp = calloc(length+1, 1) 在堆上动态分配它,或者从预分配空间上的调用传递它(该空间可能位于堆栈上)点)。

关于c - 是什么改变了我的 C 字符串中的 char 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24337298/

相关文章:

c - 在 C 中使用 free()

C - 使用 char 指针打印 int 值,未得到预期结果

ruby - 在 Ruby 中删除部分字符串(小写)并保留原始字符串(大写)

c - 这些堆栈和堆内存地址有什么区别?

c - 为什么在初始化结构时出现段错误?

c# - 哪种数据类型最适合 C++ 中 Thrift 通信中的日期时间?

C Web 浏览器下载文件

JAVA-读取混合有字符串和整数的.txt文件,将字符串存储在数组中,将整数存储在二维数组中

mysql - 在 MySQL 上用 pdo 替换字符串

c - 使用malloc分配不同行长的多维数组