C++ program error: malloc(): memory corruption [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
C++ newbie and have been writing a C++ program, but it finally breaks at the point of calling a lib function call from ctime.
The error shows info like this:
malloc(): memory corruption
AFAIK, this error(memory corruption) should be resulted from operate on out-of-bound memory address. And the print format represents YYYY-MM-DD-HH-MM, which is listed here, shows that the length should be definitively less than 100.
Additional info:
- The program is compiled with flags: "-O3 -g -Wall -Wextra -Werror -std=c++17"
- Compiler: g++ 7.4.0
- System: WSL Ubuntu-18
NOTE: This Code DOES NOT compiles and is NOT REPRODUCIBLE for the problem, See updates below
/** class file **/
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <ios>
#include <fcntl.h>
#include <algorithm>
#include <cctype>
#include <ctime>
#include <limits>
#include "cache-proxy.hpp"
static int PROXY_CONFIG = 0;
void get_timestamp(char *buffer, int len);
std::string get_cwd(void);
CacheProxy::CacheProxy(__attribute__((unused)) const std::string& node)
{
curr_dir = fs::get_cwd();
Logger::get().info("curr_dir " + curr_dir);
proxy_path = "/usr/sbin/squid";
std::string squid("squid");
char buff[200];
get_timestamp(buff, 200); // error pops
std::string proxy_config_path;
/** plenty of codes following, but commented**/
}
void ~CacheProxy(){}
void get_timestamp(char *buffer, int len)
{
time_t raw_time;
struct tm *time_info;
time(&raw_time);
time_info = std::localtime(&raw_time);
std::strftime(buffer, len, "%F-%H-%M", time_info);
return;
}
// originally from other files, for convenient to be moved into this file
std::string get_cwd(void)
{
char path[PATH_MAX];
std::string retval;
if (getcwd(path, sizeof(path)) != NULL) {
retval = std::string(path);
} else {
Logger::get().err("current_path", errno);
}
return retval;
}
/** header file **/
#pragma once
#include <string>
class CacheProxy:
{
private:
int server_pid;
std::string proxy_path;
std::string curr_dir;
std::string squid_pid_path;
;
public:
CacheProxy(const std::string&);
~CacheProxy() override;
};
/** main file **/
int main(){
Node node(); // the parameter is never used in the CacheProxy constructor though
CacheProxy proxy(node); // error pops
proxy.init();
}
Thanks for any advices or thoughts.
Updates:
code updated as above and there are three major files. The code shows the exact same sequences of the logic of my original codebase by leaving out irrelevant codes(I commented them out when run into the errors), but please forgive me in giving out such rough codes.
Basically the the error pops during the object initialization and I currently assume that problems be either in get_cwd or localtime.
Please indicate if you need more infomations, though I think other codes are non-relevant indeed.
Updates Dec 21:
After commenting out different parts of the original code, I managed to locate the error part but cannot fix the bug. Opinions from comments are indeed true that the memory corruption error should originated from somewhere beforehand, however, what I am going to do to fix this problem, is somewhat different from other answers since I use setcap for my program and cannot use valgrind in this scenarios.
I used another tool called ASan(Address Sanitizer) to do the memory check. It was really easy to find out where the memory corruption is originated from with the tool and it has comprehensive analysis when the error occurs at runtime. I added support in the compiler and found out the main problem in my case is the memory allocation for string variables in CacheProxy class.
So far, it has turned out to be another problem which is "why there are indirect memory leakages originated from allocating memory for string objects when
constructor of this class is called", which I will not collapsed here in this question.
But it is really a good lesson for me that Memory problems actually have various types and causes, you cannot stare onto the source code for solving a problem which is not "index out of bound" or "illegal address access"(segfault) problem. Many tools are really handy and specialized in dealing with these things, so go and grab your tools.

Any crash inside malloc or free is probably cause of a earlier heap corruption.
Your memory is probably corrupted earlier.
If you're using Linux, try running your program under valgrind. Valgrind can help you find out this kind of error.

The 'obvious fixes' refered to by David is:
#include <iostream>
#include <ctime>
#include <cstdio>
void get_timestamp(char *buffer, int len)
{
time_t raw_time;
struct tm *time_info;
time(&raw_time);
time_info = localtime(&raw_time); // the line of code that breaks
strftime(buffer, len, "%F-%H-%M", time_info);
return;
}
int main() {
char buff[100];
get_timestamp(buff, 100);
std::cout << std::string(buff);
return 0;
}

Related

Global function not recognized by CUDA C

I have a very complicated program and i have simplified it in order to make my problem easy to understand: I have a 2 scripts and 1 header: time_analysis.cu, DSMC_kernel_float.cu and DSMC_kernel_float.h;
Here is the time_analysis.cu
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <math.h>
#include <cutil.h>
#include <stdio.h>
#include <assert.h>
#include <memory.h>
#include <string.h>
#include <time.h>
#include <cuda_gl_interop.h>
#include <cutil_math.h>
#include "math_constants.h"
#include "vector_types.h"
#include "vector_functions.h"
typedef struct {
int seme;
} iniran;
typedef struct{
int jp1;
int jp2;
float kx;
float ky;
float kz;
} stato_struct;
stato_struct* coll_CPU=0;
stato_struct* coll2dev=0;
stato_struct* coll_GPU=0;
#include "DSMC_kernel_float.h"
//==============================================================
int main(void){
int N_thread = 4;
int ind;
coll_CPU[0].jp1= 0;
coll_CPU[1].jp2= 1;
coll_CPU[2].kx= 2;
coll_CPU[3].ky= 3;
coll_CPU[4].kz= 4;
for(ind=0;ind<=5;ind++){
coll2dev[ind]=coll_CPU[ind];
}
coll2dev=(stato_struct*) malloc(N_thread*sizeof(stato_struct));
CUDA_SAFE_CALL(cudaMalloc((void**)&coll_GPU, N_thread*sizeof(stato_struct)));
CUDA_SAFE_CALL(cudaMemcpy(coll_GPU,coll2dev,N_thread*sizeof(stato_struct), cudaMemcpyHostToDevice));
CollisioniGPU<<<4,N_thread>>>(coll_GPU);
CUT_CHECK_ERROR("Esecuzione kernel fallita");
CUDA_SAFE_CALL(cudaMemcpy(coll2dev, coll_GPU, N_thread*sizeof(stato_struct),cudaMemcpyDeviceToHost));
free(coll2dev);
CUDA_SAFE_CALL(cudaFree(coll_GPU));
free(coll_CPU);
return 0;
}
Here is the DSMC_kernel_float.cu
// Kernel della DSMC
#include "DSMC_kernel_float.h"
__global__ void CollisioniGPU(stato_struct *coll_GPU){
coll_GPU[0].vAx=1;
coll_GPU[1].vAy=1;
coll_GPU[2].vAz=1;
coll_GPU[3].tetaAp=1;
coll_GPU[4].phiAp=1;
}
Here is the DSMC_kernel_float.h
__global__ void CollisioniGPU(stato_struct* coll_GPU);
However when i type nvcc -I common/inc -rdc=true time_analysis.cu DSMC_kernel_float.cu in the terminal I get a weird message error and i don't understand why
DSMC_kernel_float.h(1): error: attribute "global" does not apply here
DSMC_kernel_float.h(1): error: incomplete type is not allowed
DSMC_kernel_float.h(1): error: identifier "stato_struct" is undefined
DSMC_kernel_float.h(1): error: identifier "coll_GPU" is undefined
DSMC_kernel_float.cu(4): error: variable "CollisioniGPU" has already been defined
DSMC_kernel_float.cu(4): error: attribute "global" does not apply here
DSMC_kernel_float.cu(4): error: incomplete type is not allowed
DSMC_kernel_float.cu(4): error: expected a ";"
At end of source: warning: parsing restarts here after previous syntax error
8 errors detected in the compilation of "/tmp/tmpxft_00003f1f_00000000-22_DSMC_kernel_float.cpp1.ii".
From what I read in the internet, I believe the error is cause by the struct but i don't understand how i could fix it to make the program work properly; how is possible that global does not apply here if i have other examples where it seems to be just fine?
Note: commom/inc is the folder provided by Nvidia in order to make Cuda compile correctly.
Regarding this statement:
Note: commom/inc is the folder provided by Nvidia in order to make Cuda compile correctly.
That's a mischaracterization. The referenced files (cutil.h and cutil_math.h) and macros (e.g. CUT_CHECK_ERROR) were provided in fairly old CUDA releases (prior to CUDA 5.0) as part of the cuda sample codes that were delivered at that time. They are not required "in order to make Cuda compile correctly." Furthermore, their use should be considered deprecated (refer to the CUDA 5.0 toolkit release notes). And if you are actually using an old toolkit like that, I would suggest upgrading to a newer one.
Regarding the compile issues, as #talonmies has pointed out, the compiler has no way of knowing what the definition of stato_struct is, when compiling any module that does not contain the definition (whether directly or included). This would be the case for your DSMC_kernel_float.cu module, which is where all your compile errors are coming from.
At first glance, it would seem that a sensible fix would be to move the typedef containing the stato_struct definition from your time_analysis.cu file into your header file (DSMC_kernel_float.h) and move the #include statement for that to the top of the time_analysis.cu file, along with your other includes.
However, it appears that your DSMC_kernel_analysis.cu file believes that there are a variety of members of that stato_struct:
__global__ void CollisioniGPU(stato_struct *coll_GPU){
coll_GPU[0].vAx=1;
coll_GPU[1].vAy=1;
coll_GPU[2].vAz=1;
coll_GPU[3].tetaAp=1;
coll_GPU[4].phiAp=1;
}
which are not part of your current definition of stato_struct:
typedef struct{
int jp1;
int jp2;
float kx;
float ky;
float kz;
} stato_struct;
So this is confusing code, and I don't think anyone else can sort that out for you. You will either need two separate struct definitions, with separate names, or else you will need to modify your stato_struct definition to include those members (.vAx, .vAy, .vAz, .tetaAp, .phiAp).
The (mis)handling of this struct definition and the resultant errors have nothing to do with CUDA. This is arising out of the C/C++ language expectations.

Segmentation Fault C++ pointers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am new to C++ programming but I know that pointers cause segmentation error. The problem is in the Readline() method when I am trying to read a sudoku but I cannot fix it. What am I missing?
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <algorithm>
#include "Sudoku.h"
using namespace std;
// Constructor
Sudoku::Sudoku(){
root=cells;
row=0;
row_ptr=&row;
}
void Sudoku::Readline(string s,int i) {
int lead;
for(int k=0;k<9;k++){
lead=(9*i)+k;
if (s[k]!=',') {
*(root+lead)=s[k];
} else {
*(root+lead)=0;
}
}
}
void Sudoku::MakeSudoku(string s){
//cout<<(*row_ptr)++<<' '<<s<<"\n";
Readline(s,(*row_ptr)++);
}
The class definition is
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Sudoku{
public:
int cells[81];
int row;
int *root;
int *row_ptr;
public:
Sudoku();
void MakeSudoku(string s);
void Readline(string s,int i);
void PrintSudoku();
};
The main file is
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include "Sudoku.cpp"
using namespace std;
int main()
{
Sudoku sd;
// Input csv file containing sudoku
ifstream filen("sudoku.csv");
string s;
if(!filen.is_open()){
cout << "Error opening file";
} else{
while(!filen.eof()){
getline(filen,s);
sd.MakeSudoku(s);
}
}
filen.close();
//sd.PrintSudoku();
return 0;
}
Your code is no C++ code. Except file operations it is (bad styled) C code. You are using a plain array (cells), you even do an unnecessary copies of the array (root) and that pointer arithemtic is dangerous (as you are currently experiencing).
I think you should rewrite your code a bit which will solve your problem:
You should use descriptive variable names... k,s,i,etc. are hard to read
Use a two-dimensional array for 'cells'. Or even better a C++ container like a vector of vectors. The latter would check boundaries and you could get rid of your pointer arithmetics (which causes such faults when done the wrong way) and you could use plain indexes.
Use proper indentions and empty lines for block separation
Don't use magic numbers like "81" and "9". Create constants. Give them names! make them dependent from each other if they are dependent.

C++ program gives a run-time error when strings are used

#include <iostream>
#include <string.h>
using namespace std;
int main ()
{
string st = "Hello world";
return 0;
}
and
#include <string>
int main ()
{
std::string st = "Hello world";
return 0;
}
I tried compiling this code using minGW compiler on netbeans. It brings up the following error after the successful build.
RUN FAILED (exit value -1,073,741,511, total time: 93ms)
But it works clean when strings are not used. I would like to know what I am doing wrong here. Thanks in advance.
Use c++ strings and don't use using namespace std:
#include <string> //c++ string header
int main ()
{
std::string st = "Hello world";
return 0;
}
#include <string.h> is the old C-style string header and most likely isn't what you want to use here. See this question for more details: Difference between <string> and <string.h>?
Note: If you really wanted the old C-style strings then you really should be using #include <cstring> because this will put those functions into the std namespace and won't cause any namespace pollution that can lead to other undesirable outcomes.
Likely what happened was that you used the old style string header and didn't properly initialize those strings. The old C-style strings don't have a constructor and operator= defined like the std::string class.
Edit: After looking at the Netbeans forum this is a problem with Netbeans and not a c++ issue. Try changing the output to an external terminal in Netbeans. Or run the program directly from the command line. If these approaches don't fix the problem or are undesirable then make a post over on the Netbeans forum. Also have a look at this question: Program won't run in NetBeans, but runs on the command line!
Uss #include <string> instead of string.h

srand(time(NULL)) "Function 'srand' could not be resolved."

I have been trying to debug this problem for a while and quite honestly, I just can't see what I'm doing wrong.
Why is there a syntax error?
#include <iostream>;
#include <time.h>;
#include <stdio.h>;
#include <stdlib.h>;
using namespace std;
class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
The error I'm getting is,
"Function 'srand' could not be resolved."
I'm well aware now that I don't need the semi-colons after 'include' statements
I'm using Eclipse CDT along with MinGW as my compiler
How I resolved the problem:
It had to do with the MinGW compiler I was using. Switching over to Visual Studio solved the problem.
; at the end of the #include directives are the problem in your code. #include directives don't need (wrong to place indeed) semicolons at the end unlike C++ statements.
[Warning] extra tokens at end of #include directive [enabled by default]
It seems any character after > in the directive causes this error/warning.
#include<iostream>a //error
Change to this:
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
class Problem3 {
public:
bool isPrime(long double num) {
srand(time(NULL));
return 0;
}
};
int main(){
cout<<"Hello Main";
}
EDIT:
Regarding the linker issue:
One suggestion is C++ expects types to be explicitly casted between types (more than C). So, use a cast to convert time_t which is returned by the time to unsigned int which is the input parameter type of srand. (And of course this might not be the problem with linker error)
Instead of using stdlib.h, try using <cstdlib>, try if it helps. Because it uses namespace.
Apart from that, I have seen this snippet here. Use that pattern if it helps.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0)); //use current time as seed for random generator
int random_variable = rand();
cout << "Random value on [0 " << RAND_MAX << "]: "
<< random_variable << '\n';
}
there is already question in SO check if that helps Eclipse Method could not be resolved in a simple program C++
Never use time() to initialize srand()..
EDIT:
Now it seems many people got this kind of problem. I found a question How do I fix Eclipse CDT Error “Function 'isdigit' could not be resolved. He is facing the same problem. The asker suggested a work around to this in his question edit.
Quoted from that question:
I now believe this to be a Code Analysis problem. A better solution is
to edit the Code Analysis options to make "Function could not be
resolved" be a warning instead of an error. That way you can see the
warnings in Problems view, but continue to work. If the function is
REALLY missing, the compiler will tell you! I also have a new theory,
that the problem is with the Code Analyzer following symlinks, because
all of the "missing" functions are in symlinked include files. Would
love any input on this theory.
Hope that points to solve the problem.
; should not be there after #include.
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include files shoule not end with ;

Odd Memory Error -- Bad Alloc

Working on a WinPCap project. Trying to do some basic pointer and memory operations and having lots of errors.
I've included the two lines I'm trying to run along with the includes.
The same lines in another VSC++ project work just fine. This is the error I am getting
Unhandled exception at 0x75a79617 in
pktdump_ex.exe: Microsoft C++
exception: std::bad_alloc at memory
location 0x0012f8e4..
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include "DataTypes.h"
#include <sstream>
#include "EthernetLayer.h"
#include <pcap.h>
int* testPointer = new int[2];
delete[] testPointer;
EDIT:
Found out something useful.
The following code snippet is what is crashing the winpcap library.
EthernetStructPointers* testData;
testData = (EthernetStructPointers*)pkt_data;
EthernetStruct newData;
memcpy(newData.DEST_ADDRESS, testData->DEST_ADDRESS, 6);
These are the definitions of the structs.
struct EthernetStructPointers
{
u_char DEST_ADDRESS[6];
u_char SOURCE_ADDRESS[6];
u_char TYPE[2];
};
struct EthernetStruct
{
u_char DEST_ADDRESS[6];
u_char SOURCE_ADDRESS[6];
u_char TYPE[2];
u_char* dataPointer;
string DestAddress;
string SourceAddress;
string Type;
int length;
};
My guess is the freestore is corrupted by one the previous statements (perhaps by an incorrect use of the pcap interface), and you only learn of the error on the next memory allocation or release, when the manager detects it and throws a bad alloc.
std::bad_alloc should be thrown when you try to new something and have run out of memory. Can you check how much free memory is available to your process?