进程退出并返回值 3221226356 [英] process get exited with return value 3221226356

查看:251
本文介绍了进程退出并返回值 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆