Char * w/ Memory Leak

时间:2015-05-12 22:45:37

标签: c++ arrays memory-leaks valgrind dynamic-memory-allocation

I have an issue identifying what is causing the memory leak in my program. Below is the code that I am running:

<?php
use Cake\Network\Http\Client;

$http = new Client();

$subscriberData = array(
    'email_address' => 'hugo@leggett.fr',
    'status' => 'subscribed',
    'merge_fields' => array(
        'FNAME' => 'Hugo',
        'LNAME' => 'Dumoulin',
        'PHONE' => '0606060606'
    )
);

$response = $http->post(
  'https://us7.api.mailchimp.com/3.0/lists/1295ff8fdb/members/',
  json_encode($subscriberData),
  array(
    'type' => 'json'
    'auth' => array(
      'type' => 'basic', 
      'username' => 'anything', 
      'password' => $MAILCHIMP_API_KEY
    )
  )
);

Running this code through valgrind, I see that I have memory that is definitely lost. To attempt to recreate the scenario and debug, I have a smaller scale version of the above code here:

char *input[999];
//exec commands
for(unsigned int i = 0; i < commands.size(); i++)
{
    string current = "";
    string word = "";
    int k = 0;
    for(unsigned int j = 0; j < commands.at(i).size(); j++) //iterate through letters
    {
        current = commands.at(i);
        //cout << "current: " << current << endl;
        if(current[j] == ' ')
        {
            input[k] = new char[word.size() + 1];
            strcpy(input[k], word.c_str());
            k++;
            word = "";
        }
        else
            word += current[j]; //add letter
        //cout << "word: " << word << endl;
    }
    input[k] = new char[word.size() + 1];
    strcpy(input[k], word.c_str());
    k++;

    input[k] = NULL;

    //...
    //...

    for(int z = 0; z <= k; z++)
    {
        delete[] input[z];
    }
}

This code does not have any memory leaks according to valgrind. What am I not de-allocating in my original code? What is my test code doing that my original code is not doing? Thank you, I appreciate any help.

2 个答案:

答案 0 :(得分:2)

如果您稍后要在代码中使用delete [],则通常需要使用new来声明您的char *。看起来只是一个简单的错误。

答案 1 :(得分:1)

我是c ++的新手,但你应该按如下方式声明输入

char **input=new char*[999];