c - 使用动态内存将 char 数组中的每个第二个元素放入另一个

标签 c

我的任务是编写一个使用动态内存的函数,它将获取一个字符串 s 并取出该字符串的每个第二个元素,然后返回一个包含这些元素的新字符串。到目前为止我的代码是:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char* skipping(const char* s)
{
    int inc = 0; //new list incrementer
    int len = strlen(s);
    char* new_s = malloc(len + 1); 
    for (int i = 0; i < len - 1; i+=2) {
        new_s[inc] = s[i];
        inc++;
    }
    return new_s;
}

int main(void)
{
    char* s = skipping("0123456789");
    printf("%s\n", s);
    free(s);
    return 0;
}

这有效,但是当我使用 Valgrind 运行它时,我被告知我有一个错误,该错误来自使用 strlen,但我似乎无法修复它。任何帮助都会很棒!

错误信息:(在 valgrind 中)

==4596== 
==4596== Conditional jump or move depends on uninitialised value(s)

==4596==    at 0x4C32D08: strlen (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)

==4596==    by 0x4EBC9D1: puts (ioputs.c:35)

==4596==    by 0x1087B4: main (in /home/ryan/ENCE260/lab6)

==4596== 

02468             //this is the expected output

==4596== 

==4596== HEAP SUMMARY:

==4596==     in use at exit: 0 bytes in 0 blocks

==4596==   total heap usage: 2 allocs, 2 frees, 1,035 bytes allocated

==4596== 

==4596== All heap blocks were freed -- no leaks are possible

==4596== 

==4596== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

最佳答案

为什么 Valgrind 报告这个错误?

来自 Valgrind online manualuse of uninitialised or unaddressable values in system calls 上:

Sources of uninitialised data tend to be:
- Local variables in procedures which have not been initialised.
- The contents of heap blocks (allocated with malloc, new, or a similar function) before you (or a constructor) write something there.

如果出现以下情况,Valgrind 会报错:

the program has written uninitialised junk from the heap block to the standard output.

因为您在 printf 中使用了 s 而没有以 null 终止它,所以它导致了错误。

关于c - 使用动态内存将 char 数组中的每个第二个元素放入另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52069899/

相关文章:

c - 如何用C语言打开nano文件

python - 自动评分器脚本 - 从文本文件读取键盘输入

c++ - 在 Windows API 中检查文件大小的规范方法?

c++ - 排序字符串 vector : plain C vs idiomatic C++11

c - 我需要帮助过滤 C 中的坏词吗?

c - C 编译器如何实现参数个数可变的函数?

c - C中线程同步和条件变量的问题

c - 打印链表没有输出

c++ - JNI如何在C/C++中调用C/C++函数?

任何人都可以解释这个按位函数来计算 log(n)