How to fix this memory leaks about strdup - valgrind

Thanks for your help, the problem has been solved!
I am a new to C, I I wondered why strdup can case memory leaks, because I free it after strup
valgrind code:
==29885==
==29885== HEAP SUMMARY:
==29885== in use at exit: 37 bytes in 2 blocks
==29885== total heap usage: 28 allocs, 26 frees, 17,131 bytes allocated
==29885==
==29885== Searching for pointers to 2 not-freed blocks
==29885== Checked 124,824 bytes
==29885==
==29885== 5 bytes in 1 blocks are indirectly lost in loss record 1 of 2
==29885== at 0x40057A1: malloc (vg_replace_malloc.c:270)
==29885== by 0x2D6B4F: strdup (in /lib/tls/i686/nosegneg/libc-2.3.4.so)
==29885== by 0x804CD3C: new_node (parser.c:355)
==29885== by 0x804C263: identifier (parser.c:75)
==29885== by 0x804940D: yyparse (vtl4.y:111)
==29885== by 0x8049FD4: main (vtl4.y:225)
==29885==
==29885== 37 (32 direct, 5 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==29885== at 0x40057A1: malloc (vg_replace_malloc.c:270)
==29885== by 0x804CCEA: new_node (parser.c:347)
==29885== by 0x804C263: identifier (parser.c:75)
==29885== by 0x804940D: yyparse (vtl4.y:111)
==29885== by 0x8049FD4: main (vtl4.y:225)
==29885==
==29885== LEAK SUMMARY:
==29885== definitely lost: 32 bytes in 1 blocks
==29885== indirectly lost: 5 bytes in 1 blocks
==29885== possibly lost: 0 bytes in 0 blocks
==29885== still reachable: 0 bytes in 0 blocks
==29885== suppressed: 0 bytes in 0 blocks
==29885==
==29885== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 12 from 8)
--29885--
--29885-- used_suppression: 12 Ubuntu-stripped-ld.so
==29885==
==29885== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 12 from 8)
new_node (parser.c:355):
struct simpleNode *new_node(JJT jjt,char *node_image){
struct simpleNode *a = malloc(sizeof(struct simpleNode));
if (a==NULL) {
yyerror("FUNC[%s]error:Init a new simple error,out of space!",__func__);
exit(0);
}
a->info.astn = jjt;
a->info.node_name = jjtNodeName[jjt];
**355>>**a->info.image = strdup(node_image);
a->info.already_rendered = cJSON_False;
a->parent = NULL;
a->firstChild = NULL;
a->nextSibling = NULL;
return a;
}
identifier (parser.c:75):
struct simpleNode* identifier(char *identifier){
printf("%s node!key:%s\n",__func__,identifier);
**75>>**struct simpleNode *a = new_node(JJTIDENTIFIER,identifier);
free(identifier);//I free it after use strdup in new_node
return a;
}
the struct simpleteNode :
struct nodeInfo {
char *image;
int already_rendered;//是否已经被渲染过了,防止子节点被重复渲染,默认为cJSON_False
JJT astn;//node编号
const char * node_name;
char *current_tpl_name;
};
struct simpleNode {
struct nodeInfo info;
struct simpleNode* firstChild;//第一个孩子
struct simpleNode* nextSibling;//右兄弟
struct simpleNode* parent;//父亲
};
at last I will free all the pointers
void free_tree(struct simpleNode* n){
//遍历
struct simpleNode *x = n;
if (x) {
//printf("==========Begin to free %s, image=%s=============\n",x->info.node_name,cJSON_Print(x->info.image));
//free_tree(x->firstChild);
//__free(x);
free_tree(x->firstChild);
free_tree(x->nextSibling);
__free(x);
//__free(x);
}
}
void free_nodeInfo(struct simpleNode* n){
if (n!=NULL) {
printf("==============begin delete %s node!\n",n->info.node_name);
struct nodeInfo ni = n->info;
free(ni.image);
// if (ni.current_tpl_name!=NULL) {
// free(ni.current_tpl_name);
// }
free(n);
printf("==============delete node done!\n");
}
}
void __free(struct simpleNode *n){
//printf("==========__free %s, image=%s=============\n",n->info.node_name,cJSON_Print(n->info.image));
//dump_tree(n);
if (n) {
//printf("==============begin delete %s node!\n",n->info.node_name);
free_nodeInfo(n);
}
}
I checked more related issues, but does not solve,please help me!

struct simpleNode* reference_index(struct simpleNode* identifier_n,
struct simpleNode* index_n) {
- struct simpleNode *a = new_node(JJTIDENTIFIER, identifier_n->info.image);//the wrong code
+ struct simpleNode *a = identifier_n;//the right code
struct simpleNode *index = new_node(JJTINDEX, "index");
addChild(index, index_n);
addChild(a, index);
}
I should not be repeated to create a new node a ,because the parameter is already a node identifier_n,when I free identifier_n ,the info.image of node a is already freed,so At this time when I free a->info.image this will cause problems.
I am sorry for my poor English.

Related

how can i fix this " valgrind tests failed;"

I got this error while all the malloc nodes are freed when I run the Valgrind test:
in use at exit: 0 bytes in 0 blocks
total heap usage: 30 allocs, 30 frees, 7,520 bytes allocated
All heap blocks were freed -- no leaks are possible
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
also this with Valgrind -v test:
WARNING: new redirection conflicts with existing -- ignoring it
old: 0x04022e10 (strlen ) R-> (0000.0) 0x580c9ce2 ???
new: 0x04022e10 (strlen ) R-> (2007.0) 0x0483f060 strlen
and this is the error report :
Conditional jump or move depends on uninitialised value(s): (file: dictionary.c, line: 95)
// Represents a node in a hash table
typedef struct node
{
char TEXT[48];
struct node *next;
}
node;
//loop over hash buckets
for (int I = 0; I < N; I++)
{
table [I] = malloc(sizeof(node)); <--- line 37
table [I]-> next = NULL;
}
here is the check function :
int x = hash(word);
node *check_ptr = table[x];
int m = strlen(word);
while (check_ptr != NULL )
{
int n = strlen(check_ptr -> TEXT);<----- line 91
"some code "
}
UPDATE - more detailed message
by 0x401C57: check (dictionary.c:91)
---- by 0x40160B: main (speller.c:113)
---- Uninitialised value was created by a heap allocation at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
---- by 0x4019C6: load (dictionary.c:37)
--- by 0x4012CE: main (speller.c:40)
WORDS IN TEXT: 10
HEAP SUMMARY: in use at exit: 0 bytes in 0 blocks
---- total heap usage: 143,122 allocs, 143,122 frees, 8,024,712 bytes allocated
All heap blocks were freed -- no leaks are possible
---- ERROR SUMMARY: 10 errors from 1 contexts (suppressed: 0 from 0)
//loop over hash buckets to initialize the all the buckets to contain null TEXT value solves the problem
it was because i never initialized the TEXT values while i was trying to access them later in the code.
for (int I = 0; I < N; I++)
{
table [I] = malloc(sizeof(node));
table [I]-> next = NULL;
**for (int u =0; u< 48 ; u++)
{
table [I]-> TEXT[u] = '0';
}**
}

Weird memory issue with ostringstream / ostream using valgrind

I get this memory issue with valgrind that I cannot make any sense out of. Just adding a line which access the ostream seems to get rid of the memory issue, but that is obviously not the way I want to go. Any ideas what could be wrong? Input to the printBuffer method is a std::ostringstream.
#define FORMATSTRWBUF(pos, buf, len, ...) pos += snprintf(buf + pos, len - pos, __VA_ARGS__)
void printBuffer(std::ostream& os, const char* buffer_name, const unsigned char* buffer, int length) const {
os << buffer_name;
os << "{length ";
os << length;
os << ", contents 0x";
// If this line is here, there is no memory issues, but...
fprintf(stdout, "\n%s %s\n", buffer_name, static_cast<std::ostringstream&>(os).str().c_str());
// fprintf(stdout, "\n%s\n", buffer_name); // having this line only has no effect
int pos = 0;
const int len = 1024;
char buf[len];
for (int32_t i = 0; i < length; ++i) {
FORMATSTRWBUF(pos, buf, len, "%02X", buffer[i]);
}
//... if it is not there is a "Conditional jump or move depends on uninitialised value(s)" memory issue here:
os << buf;
os << "}";
}
==43066== Conditional jump or move depends on uninitialised value(s)
==43066== at 0x4C2C129: strlen (vg_replace_strmem.c:454)
==43066== by 0x5687378: length (char_traits.h:263)
==43066== by 0x5687378: std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (ostream:562)
==43066== by 0x44D462: printBuffer(std::ostream&, char const*, unsigned char const*, int) const (message.h:102)
Why do you always seem to find the answer as soon as you have asked a question..
I forgot to initialize buf:
char buf[len] = {0};
did the trick.

Swift Singleton Memory Leak

I'm using a singleton as a container for localization strings, dictionary keys, and notification names used throughout the app. It is initialized as follows:
class ConstantsManager {
private init() {}
class var sharedInstance: ConstantsManager {
struct Static {
static let instance: ConstantsManager! = ConstantsManager()
}
return Static.instance
}
let localization = "NSLocalizedString(etc.)"
let dictKey = "aKey"
let notificationName = Notification.Name("name")
}
The first use of the singleton occurs in AppDelegate's application(_ application: didFinishLaunchingWithOptions:). When Instruments / Leaks reaches
let manager = ConstantsManager.sharedInstance
a leak is indicated. Does the call tree below indicate that initialization is occurring twice? I'm wondering if the properties associated with a second initialization represent the leak. Strangely, the leak doesn't occur on the simulator. (I'm using Xcode 8.2.1 and OS X 10.12.3 for iOS 10.2 deployment.)
Bytes Used # Leaks Symbol Name
448 Bytes 100.0% 14 ConstantsManager.init() -> ConstantsManager
448 Bytes 100.0% 14 ConstantsManager.__allocating_init() -> ConstantsManager
448 Bytes 100.0% 14 globalinit_33_8D935C4E2193156DAA2AB3DF99F55E80_func0
448 Bytes 100.0% 14 static ConstantsManager.(sharedInstance.getter).(Static #1).instance.unsafeMutableAddressor
448 Bytes 100.0% 14 static ConstantsManager.sharedInstance.getter
448 Bytes 100.0% 14 AppDelegate.registerUserDefaults() -> ()
448 Bytes 100.0% 14 AppDelegate.application(UIApplication, didFinishLaunchingWithOptions : [UIApplicationLaunchOptionsKey : Any]?) -> Bool
448 Bytes 100.0% 14 #objc AppDelegate.application(UIApplication, didFinishLaunchingWithOptions : [UIApplicationLaunchOptionsKey : Any]?) -> Bool
448 Bytes 100.0% 14 main

Still reachable blocks in libmosquitto

I'm working on below example but there are memory leaks when I run this with valgrind
static struct mosquitto *m = NULL;
int main(){
mosquitto_lib_init();
printf("LIBMOSQUITTO %d\n", LIBMOSQUITTO_VERSION_NUMBER);
if ((m = mosquitto_new("rtr", 1, NULL)) == NULL) {
fprintf(stderr, "Out of memory.\n");
exit(1);
}
int rc = mosquitto_tls_set(m,
"/home/ca.crt", /* cafile */
NULL, /* capath */
"/home/client.crt", /* certfile */
"/home/client.key", /* keyfile */
NULL /* pw_callback() */
);
if (rc != MOSQ_ERR_SUCCESS) {
fprintf(stderr, "Cannot set TLS CA: %s (check path names)\n",
mosquitto_strerror(rc));
exit(3);
}
#if 1
mosquitto_tls_opts_set(m,
SSL_VERIFY_PEER,
NULL, /* tls_version: "tlsv1.2", "tlsv1" */
NULL /* ciphers */
);
mosquitto_tls_insecure_set(m, 1);
#endif
if ((rc = mosquitto_connect(m, "localhost", 8884, 20)) != MOSQ_ERR_SUCCESS) {
fprintf(stderr, "%d: Unable to connect: %s\n", rc,
mosquitto_strerror(rc));
perror("");
exit(2);
}
//mosquitto_loop_forever(m, -1, 1);
mosquitto_destroy(m);
mosquitto_lib_cleanup();
}
Valgrind output:
==4264== HEAP SUMMARY:
==4264== in use at exit: 64 bytes in 2 blocks
==4264== total heap usage: 4,913 allocs, 4,911 frees, 364,063 bytes allocated
==4264==
==4264== LEAK SUMMARY:
==4264== definitely lost: 0 bytes in 0 blocks
==4264== indirectly lost: 0 bytes in 0 blocks
==4264== possibly lost: 0 bytes in 0 blocks
==4264== still reachable: 64 bytes in 2 blocks
==4264== suppressed: 0 bytes in 0 blocks
==4264== Rerun with --leak-check=full to see details of leaked memory
==4264==
==4264== For counts of detected and suppressed errors, rerun with: -v
==4264== Use --track-origins=yes to see where uninitialised values come from
==4264== ERROR SUMMARY: 13582 errors from 542 contexts (suppressed: 0 from 0)
How do I fix these?

NSSwapInt from byte array

I'm trying to implement a function that will read from a byte array (which is a char* in my code) a 32bit int stored with different endianness. I was suggested to use NSSwapInt, but I'm clueless on how to go about it. Could anyone show me a snippet?
Thanks in advance!
Heres a short example:
unsigned char bytes[] = { 0x00, 0x00, 0x01, 0x02 };
int intData = *((int *)bytes);
int reverseData = NSSwapInt(intData);
NSLog(#"integer:%d", intData);
NSLog(#"bytes:%08x", intData);
NSLog(#"reverse integer: %d", reverseData);
NSLog(#"reverse bytes: %08x", reverseData);
The output will be:
integer:33619968
bytes:02010000
reverse integer: 258
reverse bytes: 00000102
As mentioned in the docs,
Swaps the bytes of iv and returns the resulting value. Bytes are swapped from each low-order position to the corresponding high-order position and vice versa. For example, if the bytes of inv are numbered from 1 to 4, this function swaps bytes 1 and 4, and bytes 2 and 3.
There's also a NSSwapShort and NSSwapLongLong.
There is a potential of a data misalignment exception if you solve this problem by using integer pointers - e.g. some architectures require 32-bit values to be at addresses which are multiples of 2 or 4 bytes. The ARM architecture used by the iPhone et al. may throw an exception in this case, but I've no iOS device handy to test whether it does.
A safe way to do this which will never throw any misalignment exceptions is to assemble the integer directly:
int32_t bytes2int(unsigned char *b)
{
int32_t i;
i = b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24; // little-endian, or
i = b[3] | b[2] << 8 | b[1] << 16 | b[0] << 24; // big-endian (pick one)
return i;
}
You can pass this any byte pointer and it will assemble 4 bytes to make a 32-bit int. You can extend the idea to 64-bit integers if required.