2015-04-25 70 views
0

因此...有一个奇怪的。在下面的代码中,我收到一个malloc():内存损坏(快速),std :: vector和std :: stringstream

*** Error in `./a.out': malloc(): memory corruption (fast): 0x00000000011165f0 *** 

在下面的函数的while循环行。

std::vector<std::string> stringSplitter(const std::string & toSplit, char split) { 
    std::stringstream stream(toSplit); 
    std::vector<std::string> toReturn; 
    std::string current; 

    while (std::getline(stream, current, split)) 
     toReturn.push_back(current); 

    return toReturn; 
} 

我已经能够通过发送它像

SEND allenh1 passwd sup? 

重现错误,但功能按预期工作时,我把它

COMMAND allenh1 passwd room1 

任何想法?


这个函数的调用来自于以下几行的另一个功能:

FILE * fssock = fdopen(fd, "r+"); 

// Read character by character until a \n is found or the command string is full. 
    while (commandLineLength < MaxCommandLine && 
    read(fd, &newChar, 1) > 0) { 

    if (newChar == '\n' && prevChar == '\r') { 
     break; 
    } 

    commandLine[ commandLineLength ] = newChar; 
    commandLineLength++; 

    prevChar = newChar; 
} 

// Add null character at the end of the string 
// Eliminate last \r 
commandLineLength--; 
    commandLine[ commandLineLength ] = 0; 

printf("RECEIVED: %s\n", commandLine); 

std::string input(commandLine); 
std::vector<std::string> bySpace = stringSplitter(input, ' '); 
+0

此外,将输出发送到一个文本文件后,我跑了'猫-a'上该文件并没有发现无意的字符。 – allenh1

+2

我不认为这个问题出现在这段代码中。在此发布更多代码。你用哪种方式调用这个函数。从哪里获取数据? – grisha

+0

不幸的是,我不能发布太多的代码......使用gdb进行回溯后,该功能正常工作。错误来自while循环的额外运行。 – allenh1

回答

-1
vector<string> split(string str, char delimiter) { 
    vector<string> internal; 
    stringstream ss(str); // Turn the string into a stream. 
    string tok; 

    while(getline(ss, tok, delimiter)) { 
    internal.push_back(tok); 
    } 

    return internal; 
} 
+2

你必须详细说明你想表达的答案和原因。就目前而言,这没有用。 –

+0

这是你的stringSplitter的替代品,不应该引起内存错误 – samsun96

+2

你既没有解释为什么原始版本会导致内存错误,也没有解释为什么你的版本没有。只是我们相互了解,我认为这两个版本的功能都不会导致错误,而是原来的海报太懒惰,无法真正提取一个能够证明问题在其他地方的最小示例。 –