attn cpp coders

in C++ -- if you call "new" to create something (like a "Class Object", raw pointer or similar) -- you will need to also call "delete" to later free the memory used by that resource.
Without laying it on too thick for johnjohn who is just starting it out. Calling "new" should be increadibly rare. As in if we are calling it, we are probably doing something wrong. There are a lot of old tutorials out there (even though in C++98 we should still be handrolling our own smart pointers since std containers are defective with std::auto_ptr). The following:

  • std::vector should contain and control lifespan of many elements (same with list/map/etc)
  • std::unique_ptr (and std::make_unique) should contain and control lifespan of one element

So really we should never be controlling the owning pointer of an object directly in C++. Whereas in C, this is the norm (and necessary).

I would go so far as to say the only valid (and exception safe) use of new is "placement new". But honestly, this stuff isn't important at this point. Like I mentioned earlier, C++ has a lot of... cruft.
 
If you’re coming from PHP, trying to navigate std::vector and std::map is going to feel like hitting a wall of "conceptual bloat." C++ makes you pick a specific "box" for your data.

If you want to keep that PHP-style flexibility without the over-engineered mess of the STL, you should honestly be looking at Lua.

In Lua, you don't need a dozen different containers. You have one: the Table. It’s a hybrid structure—it handles sequential markers and string-indexed metadata in the exact same variable.

No headers, no templates, no nonsense.

local jpeg_data = {
filename = "vacation.jpg", -- Associative
[1] = 0xFFD8 -- Sequential/Array
}


* Zero Bloat: It’s a single structure built in pure C.
* Performance: It uses a contiguous C array for the "array part" (O(1) access) and a hash table for the rest.
* FreeBSD Native: It’s already in the base system (check the loader).
> "Tables are the sole data-structuring mechanism in Lua; they can be used to represent ordinary arrays, lists, symbol tables, sets, records, graphs, trees, etc."
> — Lua 5.4 Reference Manual, Sec 2.1
>

skip the 1,000-page C++ manuals. Use C for the "bare metal" parts and Lua for the logic....

But I am also suffering the dunning-kreuger effect having known nothing about anything coding or tech-wise until mid last year.... Maybe I stuffed up going from windows to freeBSD... Hehe
 
Without laying it on too thick for johnjohn who is just starting it out. Calling "new" should be increadibly rare. As in if we are calling it, we are probably doing something wrong. There are a lot of old tutorials out there (even though in C++98 we should still be handrolling our own smart pointers since std containers are defective with std::auto_ptr).

Yes - my explanation was to help facilitate "purposeful memory management issues using C++" so that they can be observed in valgrind(1), gdb(1), etc.

You are correct that "avoiding" memory management issues in C++ in the first place is the norm :cool:

BUT programmers also need to be able to "see" memory management issues in order to learn "how to fix them" later.
 
If you want to keep that PHP-style flexibility without the over-engineered mess of the STL, you should honestly be looking at Lua.

But I am also suffering the dunning-kreuger effect having known nothing about anything coding or tech-wise until mid last year.... Maybe I stuffed up going from windows to freeBSD... Hehe
Hello orpheus497, thanks for taking time out of your day to join the discussion. I appreciate your point-of-view.

I like PHP for web development but i'm trying to learn C/C++. I only ask how to accomplish my usage of dynamic arrays using C/C++. The concept is different but i can always look at source code for ideas/guidance. I believe that PHP is written in C.

dunning-kreuger effect? seems like anyone believeing in this concept is a victim of psychological warfare. skill is not a constant. Everyone is capable of reaching higher ground but there will always be a foot trying to kick us back down.

I remember when i was unable to grasp PHP. I wanted to build a nature website. I have over one million nature photos of birds, insects, spiders, mammals, trees and flowers etc. I couldn't figure out how to build a log-in script. I joined a PHP forum full of bullies and state-sponsored psy-war soldiers. The common ideology is that i am too stupid/my skill level is too low to program PHP. The admin offered to build me a login script for 500usd. I learned how to use sessions and databases the same evening that he made his offer. I had my own login script. 8 years later and i am reading jpeg images and scanning for malware in the data. If skill level is a constant, then i should probably give up, right?
 
When learning something new, I avoid forums in most cases. When I learned C in 1987, I only had the K&R white book. The only other person who knew C was my boss who was not one I liked talking to. So I learned by doing. Making mistakes. Figuring out why I got errors and so on.

When I started my web dev business I didn't know how to program databases. So I did the same thing. Poked around till something worked. Now that I have the internet, I would Google for things I was trying to make work and experiment with those. I avoided forums as much as I could but, when I had to ask, I just ignored the bullies and others who put you down and ask questions or say things that have nothing to do with the subject at hand.

Ask simple questions. Then experiment with what you have. Small simple code to prove it works. Then see if it fits in the whole.

You might find you gather a few helpful sources. Back in the day when everything was print magazines, I used to subscribe to maybe 15 technical magazines. Over time I whittled it down three or four. Today you can whittle that down to a couple of goto places for C questions. Or, better yet, C information sources. Those that really explain how things work in simple terms.

You'll get to a point when you start realizing you know more than those on places like reddit. If you can get the answer to your simple question, just grab it and run. Pay no attention to low-life responses. They have no meaning to you and have no affect on what you're trying to do.
 
drhowarddrfine post-752259

I am happy for your success, Sir. You are very smart and i alreay know that about you. I understand and agree with your message. I have been insulted and bullied way too many times in forums. I keep negativity out of the equation as much as possible. Sometimes i break down mentally and call myself stupid whenever i struggle with a concept. I have to get away from the subject for awhile to build my confidence level up. Sometimes whenever i get away from something for awhile, i automagically understand it better when i return to the subject. The human mind is quite powerful and amazing.

I am always happy to read a success story. I hope that you continue your success story. I wish you the best for you. I learn the most from people like you. I am always happy to meet someone with such a disposition. I learn that the world is not full of bullies and that i am not alone on this side of the tracks. Your shining light is bright and i hope that others take your advice as well.
 
Ya - there is "a completely stupid" push going on right now to stop teaching new programmers how to manage computer memory correctly. So the programmers (ALSO) don't learn how to use valgrind(1) or any other memory checking tool on their finished source code/binary because: "I don't need to do that ! The software is guaranteed to be memory safe! "

I can't tell you how many times I was fixing "memory leaks" in Java code -- but I was always told "It's Java! It can't leak memory !".
Biggest leak I ever found (and one of the first) was in Java code. Turns out it was intentional, but it still got me tons of street cred at my new (at the time) job.

Yes, Valgrind is an awesome tool. Many thanks to Dr. Paul Floyd.
 
For me it was java application server. It was starving & java had no time to run garbage collection. When it was most important. DIE it said.
 
I remember when i was exploring java applets in the early 2000s. I wasn't interested in java progrmming but i use Ulead PhotoImpact image editor. I remember that a feature of version 5 could export a java applet, so i tested the applet process. I always disabled java applets in Internet Explorer and i forgot to enable java applets, yet my test PhotoImpat applet still executed in IE. I double checked that applets were disabled, then realized that i discovered a vulnerability in IE. Microsoft issued an update within 6 months.

regarding C, i have yet to explore memory management because i am fighting with strings. I understand that C produces a compiled program and strings are stored in memory. I am not stupid. But i hate that i cannot reassign a string like an integer without memory management and a literal. Also, storing a ton of strings in the program is expensive. I am trying to come up with a way to use strings in code without storing them in memory.

combination locks come to mind. I am not a lock expert, in fact, i know how to use one. If i think about a combo lock, then i wonder how does a lock work when it has no memory? how does a lock 'know' the correct combination?

So now i wonder: has anyone designed an algorithm to output strings without storing them in memory?

I have tried to come up with something and i have it working but it needs to be better. I hate the fact that i cannot 'build' a printf statement. I have to type all of the %c options and each letters index. I'd like to figure out a lock mechanism to click through the indexes using a no-stored combo. Has anyone done this before? i could use example code.

what i have so far for a combo-lock string mechanism, which works, but the printf statements are annoying.
Code:
#include <stdio.h>
#include <stdlib.h>

char ab[] = "abcdefghijklmnopqrstuvwxyz";

void char_lock(int door, int combo) {
  switch (door) {
    case 0: //position or layout of medial tiles
      switch (combo) {
        case 0: //center
          printf("%c%c%c%c%c%c\n", ab[2], ab[4], ab[13], ab[19], ab[4], ab[17]);
          break;
        case 1: //horizontal
          printf("%c%c%c%c%c%c%c%c%c%c\n", ab[7], ab[14], ab[17], ab[8], ab[25], ab[14], ab[13], ab[19], ab[0], ab[11]);
          break;
      }
      break;
    case 1:
      break;
  }
}

int main() {
  char_lock(0, 0);
  char_lock(0, 1);
  
  return 0;
}

my thought is 'why not store the alphabet and use a combo-lock mechanism to output any string without using memory'.
 
my thought is 'why not store the alphabet and use a combo-lock mechanism to output any string without using memory'.
You don't want to store strings in memory, but you want to store a chain of letters to display?

C:
printf("%c%c%c%c\n", 'H', 'e', 'l', 'l', 'o');
printf("Hello\n");

You really think the first one is better? It's not, it's bug-prone; you lose readability and maintainability.
 
so i've finally managed to come up with a functioning character generator, which doesn't need to store strings in memory and it does not muck up the compiled exuctable with plain text everywhere. I have alot to learn about this language. I had to use integer to store the codes, which means that i have to break them up with large words. Thus, it is only the beginning of this quest. Strings are a nightmare in C/C++. I truly appreciate php a bit more today. the dot concatenator is a Holy Blessing.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char ab_ai[] = "abcdefghi";
char ab_jr[] = "jklmnopqr";
char ab_sz[] = "stuvwxyz";

void lock_cog(unsigned int table, unsigned int code, unsigned int newline, unsigned int continuity) {
  while (code > 0) {
      int modt = table % 10;
      int modc = code % 10;
      table = table / 10;
      code = code / 10;
      switch (modt) {
          case 1: putchar(ab_ai[modc]); break;
          case 2: putchar(ab_jr[modc]); break;
          case 3: putchar(ab_sz[modc]); break;
      }
  }
  if (newline && !continuity) { putchar('\n'); }
  return;
}
void char_lock(int door, int combo) {
  switch (door) {
    case 0: //position or layout of medial tiles
        switch (combo) {
          case 0: //center
              lock_cog(213211, 841442, 1, 0);
              break;
          case 1: //horizontal
              lock_cog(231221, 578857, 1, 1);
              lock_cog(2132, 2014, 1, 0);
              break;
        }
        break;
    case 1:
        break;
  } return;
}

int main() {

  char_lock(0, 0);
  char_lock(0, 1);

  return 0;
}

now i only see the alphabet arrays in a hex editor. Sweet.

EDIT: i have changed my code to the "Lock and Load" method, which uses numerical places to calculate positions in the single character array for alphabet. I am now happy with my "Lock and Load" character display version 1. Someday i'll see a better way to do this and i'll replace this code. For now, i'm moving on to learning pointers and memory management.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

char ab[] = "abcdefghijklmnopqrstuvwxyz"; 
//a=00 b=01 c=02 d=03 e=04 f=05 g=06 h=07 i=08 j=09 k=10 l=11 m=12
//n=13 o=14 p=15 q=16 r=17 s=18 t=19 u=20 v=21 w=22 x=23 y=24 z=25

void char_load(unsigned int tens, unsigned int ones, uint8_t newline, uint8_t continuity) {
  uint8_t mt = {0}, mo = {0};
  while (ones > 0) {
      mt = tens % 10;
      mo = ones % 10;
      mo += 10 * mt;
      tens = tens / 10;
      ones = ones / 10;
      putchar(ab[mo]);
  }
  if (newline && !continuity) { putchar('\n'); }
  return;
}
void char_lock(int door, int combo) {
  switch (door) {
    case 0: //position or layout of medial tiles
        switch (combo) {
          case 0: //center
              char_load(101100, 749342, 1, 0);
              break;
          case 1: //horizontal
              char_load(120110, 458747, 1, 1);
              char_load(1011, 1093, 1, 0);
              break;
        }
        break;
    case 1:
        break;
  } return;
}

int main() {

  char_lock(0, 0);
  char_lock(0, 1);

  return 0;
}
 

Attachments

  • sourceprintf.jpg
    sourceprintf.jpg
    35.4 KB · Views: 23
  • charlock.jpg
    charlock.jpg
    158.1 KB · Views: 24
  • alphabet.jpg
    alphabet.jpg
    17.3 KB · Views: 24
I am adding closure to this thread. I have been studying alot of c lately and i know that i will need years to master this language before learning C++. Alot of members here are years ahead of me and my progression through the language depends upon the information that i can find for self-learning.

Meantime i have added a structure to my grid graph code, which i am only using as a project to begin learning C. As a side note, i didn't convert my php code properly, so the calculate center is not working correctly in my previous posts. I have corrected the data and updated my project. The problem with this particular project is that it is quite large and i cannot allow large numbers in php alone. C language is also not possible because large numbers will destroy memory quickly. A loop with 1920x1080 will create a loop of over 2 million tiles to display (i build the grid graph dynamically and display it using svg in php). I have researched embedding sql lite into a c program and i have the foundation for using a database to store the pre-calculated grid graph data. Thus, if i were to create software for this grid-graph app in C language, then i will store the data in a db instead of calculating it live. My PHP Grid Graph code calculates a ton of data: center tiles, perimeters, diagonals, tensive diagonals, neighbors NESW, right triangles contained in the graph in both directions et cetera. i created this code to answer a PHP question about breaking connections (edges/vertices) but allowing all tiles to still be accessible. So i also have a custom 'cycle/circuit breaker' algotithm in use, which also counts and stores all of the graph cycles in an array. I use arrays in PHP and this is no good in C (major memory problem.) Anyway, this graph code was just a way to begin learning C.

Code:
//cc -lm -o gg ~/gg6.c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <stdbool.h>

struct Grid_Graph {
  unsigned int cols_m; //number of columns as m
  struct {
    bool cols_m_parity; //columns m parity bit
    unsigned int cols_m_plus_1;
    unsigned int cols_m_minus_1;
    unsigned int cols_m_minus_2;
  };
  unsigned int rows_n; //number of rows as n
  struct {
    bool rows_n_parity; //rows n parity bit
    unsigned int rows_n_plus_1;
    unsigned int rows_n_minus_1;
  };
  unsigned int spaces; //m*n as vertex spaces
} gg;

void clear_screen() {
  int system(const char *command);
  system("clear");
  return;
}

unsigned int cli_prompts(unsigned int stage, unsigned int type) {
  unsigned int passes = 0; //loop safety control

  switch (stage) {
    case 0: //get the dimensions of the grid graph
      clear_screen();
      printf("Grid Graph Dimensions (range 3-to-2000)\n");
      printf("columns: %u, rows: %u, spaces: %u\n", gg.cols_m, gg.rows_n, gg.spaces);
      printf("%s: ", type == 0 ? "Enter number of columns (m)": "Enter number of rows (n)");
      while(1) {
          if (passes > 2) {
            clear_screen();
            printf("gg: Too many attempts without a valid response.\nGoodbye.\n");
            break;
          }
          int input_status = scanf("%u", &type);
          if (input_status == 1) {
              if (type > 2 && type <= 2000) { break; }
          }
          while(getchar() != '\n');
          type = 0; passes++;
       }
    break;
  }
  return type;
}

void calculate_center() {
  unsigned int half = floor((gg.spaces + 1) / 2);
  unsigned int halves = half + 1;
  unsigned int tile1 = half - floor(half / gg.rows_n);
  unsigned int tile2 = tile1 + 1;
  unsigned int tile3 = tile1 + gg.cols_m;
  unsigned int tile4 = tile3 + 1;
  
  printf("Medial spaces\n");
  if (gg.cols_m_parity) { //warning: bool with switch.
      if (gg.rows_n_parity) {
          printf("  count: 4\n  id: %u, %u, %u, %u\n  position: stack\n", tile1, tile2, tile3, tile4);
      } else {
          printf("  count: 2\n  id here: %u, %u\n  position: horizontal\n", half, halves);
      }
  } else {
      if (gg.rows_n_parity) {
          printf("  count: 2\n  id: %u, %u\n  position: vertical\n", tile1, tile3);
      } else {
          printf("  count: 1\n  id: %u\n  position: center\n", half);
      }
  }
  return;
}

int main(void) {
    gg.cols_m = cli_prompts(0, 0); if (!gg.cols_m) { return 1; }
    gg.rows_n = cli_prompts(0, 1); if (!gg.rows_n) { return 1; }
    gg.cols_m_plus_1 = gg.cols_m + 1;
    gg.cols_m_minus_1 = gg.cols_m - 1;
    gg.cols_m_minus_2 = gg.cols_m - 2;
    gg.rows_n_plus_1 = gg.rows_n + 1;
    gg.rows_n_minus_1 = gg.rows_n - 1;

    gg.spaces = gg.cols_m * gg.rows_n;
    gg.cols_m_parity = gg.cols_m %2 ? 0: 1;
    gg.rows_n_parity = gg.rows_n %2 ? 0: 1;

    clear_screen();
    printf("columns: %u, rows: %u, spaces: %u\n", gg.cols_m, gg.rows_n, gg.spaces);
    printf("m parity: %d\nn parity: %d\n", gg.cols_m_parity, gg.rows_n_parity);
    printf("\n");
    calculate_center();

    printf("\nm+1= %u, n+1= %u\n", gg.cols_m_plus_1, gg.rows_n_plus_1);
    printf("m-1= %u, n-1= %u\n", gg.cols_m_minus_1, gg.rows_n_minus_1);
  //to test exit status from sh/bourne shell: echo $?
  return 0;
}

Since my last post, i have learned how to create a gui app using Xlib.h and i made my first window. I have also learned how to embedd sqllite directly in the C program and store the data in a file (instead of memory).

I realize how much learning is involved with this quest, so i will consider this thread closed. I have alot of class time ahead of me. However, i am going to attempt building my first Xlib GUI C program. I want to make a Wordle like game in English/German for FreeBSD.

For now, Thank you to everyone offering advice in this thread. Much appreciated. Everyone has helped me get started with C/C++ and i will remember the kindness exhibited here. I never forget those individuals that help me in my quests.
 
Back
Top