使用动态内存将char数组中的每一个元素转换为另一个元素
我的任务是编写一个使用动态内存的函数,它将获取一个字符串使用动态内存将char数组中的每一个元素转换为另一个元素,c,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);
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报告这个错误 从上的Valgrind: 未初始化数据的来源往往是:
-程序中未初始化的局部变量。
-堆块的内容(使用malloc、new或类似函数分配)在您(或构造函数)在那里写入内容之前 Valgrind将在以下情况下投诉: 程序已将未初始化的垃圾从堆块写入标准输出
由于您在
printf
中使用了s
,但没有使用null终止,因此导致了错误。错误是什么?请发布一个。这包括您的整个程序的副本和您收到的实际错误消息。我的水晶球说错误在not null中。为什么i
?可能不是错误,但我不确定为什么在循环条件中使用len-1
而不是len
。另外,您在复制后没有终止new\s
,只是添加了其他信息,很抱歉这是我第一次发布:)1)返回new\s代码>=>new_s[inc]='\0';返回新的_代码>2)i==>i3)malloc(len+1)代码>==>malloc((len+3)/2)代码>
==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)