如何从函数中获取内存块并将其写入文件?

时间:2022-08-26 22:14:38

I want to write the data "somebytes" that I get from a function called NextUnit() to a file named "output.txt", but the code that I wrote does not work. When I open the file, it does not look like my "somebytes". Here is the code:

我想把我从一个名为NextUnit()的函数中得到的数据“somebytes”写成一个名为“output.txt”的文件,但是我编写的代码不起作用。当我打开文件时,它看起来不像我的“somebytes”。这是代码:

#include <stdio.h>
#include <string.h>

char* NextUnit()
{
    char Unit[256];
    strcpy(Unit,"somebytes");
    return &Unit[0];
}

int main()
{
    FILE *ourfile;
    ourfile=fopen("output.txt","wb");
    char* somedata;
    somedata=NextUnit();
    printf("%s\n",somedata);
    fwrite(somedata,1,strlen(somedata),ourfile); 
    fclose(ourfile);
}

9 个解决方案

#1


You are returning the local address from a function (aka released stack address). Which is then changed once you call the next function.

您正在从函数(也称为已发布的堆栈地址)返回本地地址。一旦调用下一个函数,它就会被更改。

Ether just return a global constant

以太只返回一个全局常量

const char* NextUnit() { return "somebytes"; }

or copy it into a new memory structure, which you will then need to also free later...

或者将其复制到一个新的内存结构中,然后您需要稍后释放...

char* NextUnit() 
{ 
    char* newstr = new char[256]; 
    strcpy(newstr,"somebytes"); 
    return newstr;
}

// some code later
char* tmpstr = NextUnit();

// do writing stuff

// free memory
delete tmpstr;

#2


You've declared Unit[256] on the stack in a subprocedure. But when your NextUnit() returns, the variable that was scoped to it goes out of scope, and you are no longer pointing to valid memory.

您已在子过程中在堆栈上声明Unit [256]。但是当你的NextUnit()返回时,作用域的变量超出范围,你不再指向有效的内存。

Consider allocating the memory with new, and then releasing it in the caller, or having the caller pass down a pointer to preallocated memory.

考虑使用new分配内存,然后在调用者中释放它,或者让调用者向下传递指向预分配内存的指针。

#3


you are returning the local address of a function. Ether just return

您正在返回函数的本地地址。以太只是回归

const char* NextUnit() { return "somebytes"; }

const char * NextUnit(){return“somebytes”; }

so it's constant, or copy it into a new memory stucture, which you will then need to also free later...

所以它是不变的,或者将它复制到一个新的内存结构中,然后你需要稍后释放...

I don't have enough mojo to comment on the quoted answer, so I have to put this as a new answer.

我没有足够的魔力来评论引用的答案,所以我必须把它作为一个新的答案。

His answer is trying to say the right thing, but it came out wrong.

他的回答是试图说出正确的话,但它出错了。

Your code is returning the address of a local variable inside the NextUnit() function. Don't do that. Its bad. Do what he suggested.

您的代码返回NextUnit()函数内的局部变量的地址。不要那样做。这不好。做他的建议。

#4


If you are using C++, the following is a much better way to go about this:

如果您使用的是C ++,以下是更好的方法:

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char ** argv)
{
    ofstream outFile;

    outFile.open("output.txt");
    outFile << "someBytes";
    outFile.close();

    return 0;
}

And, once you are comfortable with that, the next thing to learn about is RAII.

而且,一旦你对此感到满意,接下来要了解的是RAII。

#5


I would rewrite it like this:

我会像这样重写它:

char *NextUnit(char *src)
{
    strcpy(src, "somebytes");
    return src;
}

This way you can decide what to do with the variable outside the function implementation:

通过这种方式,您可以决定如何处理函数实现之外的变量:

char Unit[256];
char *somedata = NextUnit(Unit);

#6


NextUnit returns the address of Unit, which is an array local to that function. That means that it is allocated on the stack, and "released" when the function returns, making the return value non-valid.

NextUnit返回Unit的地址,Unit是该函数的本地数组。这意味着它在堆栈上分配,并在函数返回时“释放”,使返回值无效。

To solve this problem you can:

要解决此问题,您可以:

  • Dynamically allocate a new string each time NextUnit is called. Note that in that case you will have to delete the memory afterwards.
  • 每次调用NextUnit时动态分配一个新字符串。请注意,在这种情况下,您将不得不删除内存。

  • Create a global string. That's fine for a small "test" application, but generally use of global variables is discouraged.
  • 创建一个全局字符串。这对于小型“测试”应用程序来说很好,但是通常不鼓励使用全局变量。

  • Have main allocate a string (either dynamically or on the stack), pass it as a parameter to NextUnit, and have NextUnit copy to that string.
  • 主要分配一个字符串(动态或在堆栈上),将其作为参数传递给NextUnit,并将NextUnit复制到该字符串。

#7


You have a few problems here. The main one, I think, is that NextUnit() is allocating the buffer on the stack and you're effectively going out of scope when you try to return the address.

你这里有一些问题。我认为主要的是NextUnit()在堆栈上分配缓冲区,当你尝试返回地址时,你实际上已经超出了范围。

You can fix this in a C-style solution by mallocing space for the buffer and returning the pointer that malloc returns.

您可以通过为缓冲区mallocing空间并返回malloc返回的指针,在C风格的解决方案中解决此问题。

I think a first step might be to rewrite the code to something more like the following:

我认为第一步可能是将代码重写为更像以下内容:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* NextUnit()
{
    char *Unit = (char *)malloc( 256 );
    memset(Unit, 0, sizeof(Unit));
    strcpy(Unit,"somebytes");
    return Unit;
}

int main()
{
    FILE *ourfile;
    ourfile=fopen("output.txt","wb");
    char* somedata;
    somedata=NextUnit();
    printf("%s\n",somedata);
    //fwrite(somedata,1,strlen(somedata),ourfile);
    fprintf(ourfile, somedata); 
    free(somedata);
    fclose(ourfile);
}

#8


"Unit" declared as a local variable inside NextUnit which is actually a "stack" variable meaning that it's lifetime is only as long as NextUnit hasn't returned.

“Unit”在NextUnit中声明为局部变量,实际上是一个“堆栈”变量,这意味着它的生命周期只有NextUnit没有返回。

So, while NextUnit hasn't returned yet, copying "somebytes" to it is ok, as is printing it out. As soon as NextUnit returns, Unit is released from the stack and the pointer somedata in main will not be pointing to something valid.

因此,虽然NextUnit尚未返回,但将“somebytes”复制到它是正常的,就像将其打印出来一样。一旦NextUnit返回,Unit就会从堆栈释放,而main中的指针somedata将不会指向有效的东西。

Here is quick fix. I still don't recommend writing programs this way this way, but it's the least changes.

这是快速修复。我仍然不建议以这种方式编写程序,但这是最少的变化。

#include <stdio.h>
#include <string.h>

char Unit[256];

char* NextUnit()
{

    strcpy(Unit,"somebytes");
    return &Unit[0];
}

int main()
{
    FILE *ourfile;
    ourfile=fopen("output.txt","wb");
    char* somedata;
    somedata=NextUnit();
    printf("%s\n",somedata);
    fwrite(somedata,1,strlen(somedata),ourfile); 
    fclose(ourfile);
}

That works but it's kindof pointless returning the address of Unit when it's actually Global!

这是有效的,但当它实际上是Global时,它返回Unit的地址是毫无意义的!

#9


Declare Unit as static:

将单位声明为静态:

char* NextUnit()
{
  static char Unit[256];
  strcpy(Unit,"somebytes");
  return &Unit[0];
}

But if you use C++ compiler you should consider using std::string instead of char*. std::string is more safe and will do all allocation/deallocation jobs for you.

但是如果你使用C ++编译器,你应该考虑使用std :: string而不是char *。 std :: string更安全,将为您执行所有分配/释放作业。

#1


You are returning the local address from a function (aka released stack address). Which is then changed once you call the next function.

您正在从函数(也称为已发布的堆栈地址)返回本地地址。一旦调用下一个函数,它就会被更改。

Ether just return a global constant

以太只返回一个全局常量

const char* NextUnit() { return "somebytes"; }

or copy it into a new memory structure, which you will then need to also free later...

或者将其复制到一个新的内存结构中,然后您需要稍后释放...

char* NextUnit() 
{ 
    char* newstr = new char[256]; 
    strcpy(newstr,"somebytes"); 
    return newstr;
}

// some code later
char* tmpstr = NextUnit();

// do writing stuff

// free memory
delete tmpstr;

#2


You've declared Unit[256] on the stack in a subprocedure. But when your NextUnit() returns, the variable that was scoped to it goes out of scope, and you are no longer pointing to valid memory.

您已在子过程中在堆栈上声明Unit [256]。但是当你的NextUnit()返回时,作用域的变量超出范围,你不再指向有效的内存。

Consider allocating the memory with new, and then releasing it in the caller, or having the caller pass down a pointer to preallocated memory.

考虑使用new分配内存,然后在调用者中释放它,或者让调用者向下传递指向预分配内存的指针。

#3


you are returning the local address of a function. Ether just return

您正在返回函数的本地地址。以太只是回归

const char* NextUnit() { return "somebytes"; }

const char * NextUnit(){return“somebytes”; }

so it's constant, or copy it into a new memory stucture, which you will then need to also free later...

所以它是不变的,或者将它复制到一个新的内存结构中,然后你需要稍后释放...

I don't have enough mojo to comment on the quoted answer, so I have to put this as a new answer.

我没有足够的魔力来评论引用的答案,所以我必须把它作为一个新的答案。

His answer is trying to say the right thing, but it came out wrong.

他的回答是试图说出正确的话,但它出错了。

Your code is returning the address of a local variable inside the NextUnit() function. Don't do that. Its bad. Do what he suggested.

您的代码返回NextUnit()函数内的局部变量的地址。不要那样做。这不好。做他的建议。

#4


If you are using C++, the following is a much better way to go about this:

如果您使用的是C ++,以下是更好的方法:

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char ** argv)
{
    ofstream outFile;

    outFile.open("output.txt");
    outFile << "someBytes";
    outFile.close();

    return 0;
}

And, once you are comfortable with that, the next thing to learn about is RAII.

而且,一旦你对此感到满意,接下来要了解的是RAII。

#5


I would rewrite it like this:

我会像这样重写它:

char *NextUnit(char *src)
{
    strcpy(src, "somebytes");
    return src;
}

This way you can decide what to do with the variable outside the function implementation:

通过这种方式,您可以决定如何处理函数实现之外的变量:

char Unit[256];
char *somedata = NextUnit(Unit);

#6


NextUnit returns the address of Unit, which is an array local to that function. That means that it is allocated on the stack, and "released" when the function returns, making the return value non-valid.

NextUnit返回Unit的地址,Unit是该函数的本地数组。这意味着它在堆栈上分配,并在函数返回时“释放”,使返回值无效。

To solve this problem you can:

要解决此问题,您可以:

  • Dynamically allocate a new string each time NextUnit is called. Note that in that case you will have to delete the memory afterwards.
  • 每次调用NextUnit时动态分配一个新字符串。请注意,在这种情况下,您将不得不删除内存。

  • Create a global string. That's fine for a small "test" application, but generally use of global variables is discouraged.
  • 创建一个全局字符串。这对于小型“测试”应用程序来说很好,但是通常不鼓励使用全局变量。

  • Have main allocate a string (either dynamically or on the stack), pass it as a parameter to NextUnit, and have NextUnit copy to that string.
  • 主要分配一个字符串(动态或在堆栈上),将其作为参数传递给NextUnit,并将NextUnit复制到该字符串。

#7


You have a few problems here. The main one, I think, is that NextUnit() is allocating the buffer on the stack and you're effectively going out of scope when you try to return the address.

你这里有一些问题。我认为主要的是NextUnit()在堆栈上分配缓冲区,当你尝试返回地址时,你实际上已经超出了范围。

You can fix this in a C-style solution by mallocing space for the buffer and returning the pointer that malloc returns.

您可以通过为缓冲区mallocing空间并返回malloc返回的指针,在C风格的解决方案中解决此问题。

I think a first step might be to rewrite the code to something more like the following:

我认为第一步可能是将代码重写为更像以下内容:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* NextUnit()
{
    char *Unit = (char *)malloc( 256 );
    memset(Unit, 0, sizeof(Unit));
    strcpy(Unit,"somebytes");
    return Unit;
}

int main()
{
    FILE *ourfile;
    ourfile=fopen("output.txt","wb");
    char* somedata;
    somedata=NextUnit();
    printf("%s\n",somedata);
    //fwrite(somedata,1,strlen(somedata),ourfile);
    fprintf(ourfile, somedata); 
    free(somedata);
    fclose(ourfile);
}

#8


"Unit" declared as a local variable inside NextUnit which is actually a "stack" variable meaning that it's lifetime is only as long as NextUnit hasn't returned.

“Unit”在NextUnit中声明为局部变量,实际上是一个“堆栈”变量,这意味着它的生命周期只有NextUnit没有返回。

So, while NextUnit hasn't returned yet, copying "somebytes" to it is ok, as is printing it out. As soon as NextUnit returns, Unit is released from the stack and the pointer somedata in main will not be pointing to something valid.

因此,虽然NextUnit尚未返回,但将“somebytes”复制到它是正常的,就像将其打印出来一样。一旦NextUnit返回,Unit就会从堆栈释放,而main中的指针somedata将不会指向有效的东西。

Here is quick fix. I still don't recommend writing programs this way this way, but it's the least changes.

这是快速修复。我仍然不建议以这种方式编写程序,但这是最少的变化。

#include <stdio.h>
#include <string.h>

char Unit[256];

char* NextUnit()
{

    strcpy(Unit,"somebytes");
    return &Unit[0];
}

int main()
{
    FILE *ourfile;
    ourfile=fopen("output.txt","wb");
    char* somedata;
    somedata=NextUnit();
    printf("%s\n",somedata);
    fwrite(somedata,1,strlen(somedata),ourfile); 
    fclose(ourfile);
}

That works but it's kindof pointless returning the address of Unit when it's actually Global!

这是有效的,但当它实际上是Global时,它返回Unit的地址是毫无意义的!

#9


Declare Unit as static:

将单位声明为静态:

char* NextUnit()
{
  static char Unit[256];
  strcpy(Unit,"somebytes");
  return &Unit[0];
}

But if you use C++ compiler you should consider using std::string instead of char*. std::string is more safe and will do all allocation/deallocation jobs for you.

但是如果你使用C ++编译器,你应该考虑使用std :: string而不是char *。 std :: string更安全,将为您执行所有分配/释放作业。