进程退出并返回值 3221226356

编程入门 行业动态 更新时间:2024-10-22 21:26:20
本文介绍了进程退出并返回值 3221226356的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

每当我运行以下代码,并输入长字符串时,它就会以返回值 3221226356 退出

Whenever I run the following code, and give input as long string it gets exited with the return value 3221226356

#include<stdio.h> #include<stdlib.h> #include<string.h> int main() { int i=0; char c,*input; input=(char *)malloc(sizeof(char)); if(input==NULL) { printf("Could not allocate memory"); exit(1); } printf("%d size",strlen(input)); printf("Enter the string: "); while((c=getchar())!='\n') { realloc(input, (sizeof(char))); input[i++]=c; } printf("%s",input); }

推荐答案

realloc 函数返回一个 new 指针.它不会改变你传递给它的指针.

The realloc function returns a new pointer. It doesn't change the pointer you pass to it.

这意味着在第一次调用 realloc 之后,您可能开始写入未分配的内存,导致 未定义行为.

That means after the first call to realloc you probably start writing to unallocated memory, leading to undefined behavior.

另请注意,您的 realloc 调用仅分配 一个 字节.您需要分配之前的尺寸加一个.

Also note that your realloc call only allocates one byte. You need to allocate the previous size plus one.

还有一个问题是您在指向未初始化内存(顺便说一下大小为 1)的指针上调用 strlen,这也导致未定义的行为.

There's also the problem of you calling strlen on a pointer to uninitialized memory (of size one by the way), which also leads to undefined behavior.

并且由于您将分配的内存视为字符串,因此您还应该为字符串终止符分配空间,因此第一次分配应该是两个字节.

And since you treat the memory you allocate as a string, you should also allocate space for the string terminator, so the very first allocation should be for two bytes.

另外几个注意事项:sizeof(char) 被指定为总是导致 1.在 C 不要转换 malloc 的结果(和家人).

Another couple of notes: sizeof(char) is specified to always result in 1. And in C don't cast the result of malloc (and family).

更多推荐

进程退出并返回值 3221226356

本文发布于:2023-06-04 19:10:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/503361.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返回值   进程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!