如何在C使用的strtok正常,所以没有内存泄漏? [英] How to use strtok in C properly so there is no memory leak?

查看:748
本文介绍了如何在C使用的strtok正常,所以没有内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点用,当你调用的strtok在C的字符指针我知道它修改字符串的内容,所以如果我打电话的strtok在一个名为线,其内容将改变变量会发生什么混淆。假设我按下面的方法:

  void函数myFunc的(字符*线){    //得到一个指向原来的内存块
    字符* garbageLine =行;    // 做一些工作
    //调用的行多次strtok的,直到它返回NULL
    //做更多的工作    免费(garbageLine);
}

再假设它被传递给myFunc的前线被malloced。我应该使用免费或strtok函数它为我们所做的工作后,原字符串?另外,如果'行'是不是malloced会发生什么,我尝试使用上面的功能?它是更安全做到以下几点呢? (假设程序员不会打电话免费的,如果他知道了行不malloced)

调用

 的char * garbageLine =行;
myFunc的(线);
免费(garbageLine);

函数定义

  void函数myFunc的(字符*线){
    // 做一些工作
    //调用的行多次strtok的,直到它返回NULL
    //做更多的工作
}


解决方案

的strtok()不会释放任何东西,因为它没有字符串的存储位置的知识。这可能是栈或堆,它不知道或不关心的! :)


  

时可以更安全地做,而不是下面的?


您第二个例子是好得多,因为它简化了myFunc的(),并使得它在更多的情况下有用,因为该函数不需要知道该字符串被分配。通过从myFunc的除去呼叫释放()()你能够使用该函数来分析从堆栈或堆串。来电者分配内存,调用者释放内存!

延伸阅读:
的strtok()

I am somewhat confused by what happens when you call strtok on a char pointer in C. I know that it modifies the contents of the string, so if I call strtok on a variable named 'line', its content will change. Assume I follow the bellow approach:

void function myFunc(char* line) {

    // get a pointer to the original memory block
    char* garbageLine = line;

    // Do some work
    // Call strtok on 'line' multiple times until it returns NULL
    // Do more work

    free(garbageLine);
}

Further assume that 'line' is malloced before it is passed to myFunc. Am I supposed to free the original string after using strtok or does it do the job for us? Also, what happens if 'line' is not malloced and I attempt to use the function above? Is it safer to do the following instead? (Assume the programmer won't call free if he knows the line is not malloced)

Invocation

char* garbageLine = line;
myFunc(line);
free(garbageLine);

Function definition

void function myFunc(char* line) {
    // Do some work
    // Call strtok on 'line' multiple times until it returns NULL
    // Do more work
}

解决方案

strtok() will not free anything, as it has no knowledge of where the string is stored. It could be on the stack or the heap, it doesn't know or care! :)

Is it safer to do the following instead?

Your second example is much better, as it simplifies myFunc(), and makes it useful in more situations as the function does not need to know where the string is allocated. By removing the call to free() from myFunc() you are able to use the function to parse strings from the stack or the heap. The caller allocates the memory, the caller frees the memory!

Further reading: strtok()

这篇关于如何在C使用的strtok正常,所以没有内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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